class ImmortalSnakeGame {
  constructor() {
    this.canvas = document.getElementById('gameCanvas');
    this.ctx = this.canvas.getContext('2d');
    this.cellSize = 30;
    this.gridWidth = Math.floor(this.canvas.width / this.cellSize);
    this.gridHeight = Math.floor(this.canvas.height / this.cellSize);
    
    // 不再使用图片，改为圆形绘制
    
    this.snake = [{ x: 10, y: 10 }, { x: 9, y: 10 }]; // 默认长度为2
    this.direction = { x: 1, y: 0 };
    this.food = this.generateFood();
    this.score = 0;
    this.spirit = 0; // 灵力值
    this.gameRunning = false;
    this.isPaused = false;
    this.gameSpeed = 150;
    this.autoPlay = false;
    
    // 修仙境界系统
    this.realms = [
      { name: '凡蛇期', threshold: 0, color: '#40E0D0', size: 1.0, background: 'step-1.jpg', video: 'step-1.mp4', audio: 'step-1-尘焰怒燃.mp3', food: 'food-1.png' },    // 青绿
      { name: '筑基期', threshold: 5, color: '#1E90FF', size: 1.2, background: 'step-2.jpg', video: 'step-2.mp4', audio: 'step-2-气海沸腾.mp3', food: 'food-2.png' },   // 碧蓝
      { name: '金丹期', threshold: 12, color: '#FFD700', size: 1.4, background: 'step-3.jpg', video: 'step-3.mp4', audio: 'step-3-丹破九霄.mp3', food: 'food-3.png' },   // 金黄
      { name: '元婴期', threshold: 22, color: '#9932CC', size: 1.6, background: 'step-4.jpg', video: 'step-4.mp4', audio: 'step-4-灵胎裂世.mp3', food: 'food-4.png' },   // 紫金
      { name: '化神期', threshold: 35, color: '#FF6347', size: 1.8, background: 'step-5.jpg', video: 'step-5.mp4', audio: 'step-5-劫尽龙啸.mp3', food: 'food-5.png' },   // 赤金
      { name: '飞升期', threshold: 50, color: '#F5F5DC', size: 2.0, background: 'step-6.jpg', video: 'step-6.mp4', audio: 'step-6-万象崩天.mp3', food: 'food-6.png' }   // 白金
     ];
    
    this.currentRealm = this.realms[0];
    
    // 粒子系统
    this.particles = [];
    
    // 背景音乐系统
    this.currentAudio = null;
    
    // 食物图片预加载
    this.foodImages = {};
    this.loadFoodImages();
    
    // 最高境界记录
    this.highestRealm = this.loadHighestRealm();
    this.updateHighScoreDisplay();
    
    // 难度系统
    this.difficulty = 2; // 默认普通难度
    this.difficultyMultipliers = {
      1: 0.8,  // 简单
      2: 1.0,  // 普通
      3: 1.3,  // 困难
      4: 1.6,  // 地狱
      5: 2.0   // 修罗
    };
    
    this.difficultyNames = {
      1: '简单',
      2: '普通', 
      3: '困难',
      4: '地狱',
      5: '修罗'
    };
    
    // 网格缓存系统
    this.gridCache = new Map();
    this.lastGridRealm = null;
    this.gridCacheCanvas = null;
    this.gridCacheCtx = null;
    
    // 移动端检测
    this.isMobile = this.detectMobileDevice();
    
    // 神通技能系统
    this.skills = {
      lingqiHuti: {
        name: '灵气护体',
        realmIndex: 1, // 筑基期
        cooldown: 0, // 被动技能，无冷却
        lastUsed: 0,
        active: false, // 被动技能，始终激活
        duration: 0, // 被动技能，无持续时间限制
        activatedAt: 0,
        passive: true // 标记为被动技能
      },
      shunyiShu: {
        name: '瞬移术',
        realmIndex: 2, // 金丹期
        cooldown: 25000, // 25秒冷却
        lastUsed: 0
      },
      autoXiuxian: {
        name: '元婴化身',
        realmIndex: 3, // 元婴期
        cooldown: 5000, // 5秒冷却
        lastUsed: 0,
        spiritGain: 2 // 立即增加2点灵力
      },
      longweiZhenshe: {
        name: '龙威震慑',
        realmIndex: 4, // 化神期
        cooldown: 15000, // 15秒冷却
        lastUsed: 0,
        active: false,
        duration: 3000, // 3秒持续时间
        activatedAt: 0
      },
      tiandaoLunhui: {
        name: '天道轮回',
        realmIndex: 5, // 飞升期
        cooldown: 60000, // 60秒冷却，每局只能用一次
        lastUsed: 0,
        used: false // 每局游戏标记
      }
    };
    
    // 技能效果状态
    this.skillEffects = {
      timeSlowFactor: 1.0, // 时间减速因子
      invulnerable: false // 无敌状态
    };
    
    this.setupEventListeners();
  }

  // 检测移动端设备
  detectMobileDevice() {
    const userAgent = navigator.userAgent || navigator.vendor || window.opera;
    const mobileRegex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
    const touchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
    const smallScreen = window.innerWidth <= 768;
    
    return mobileRegex.test(userAgent) || touchDevice || smallScreen;
  }

  // 初始化虚拟按键
  initVirtualControls() {
    const virtualControls = document.getElementById('virtualControls');
    if (this.isMobile && virtualControls) {
      virtualControls.style.display = 'block';
      this.setupVirtualControlEvents();
    }
  }

  // 设置虚拟按键事件
  setupVirtualControlEvents() {
    const virtualButtons = document.querySelectorAll('.virtual-btn');
    
    virtualButtons.forEach(button => {
      // 触摸开始事件
      button.addEventListener('touchstart', (e) => {
        e.preventDefault();
        const direction = button.getAttribute('data-direction');
        this.handleVirtualDirection(direction);
      });
      
      // 鼠标点击事件（用于桌面端测试）
      button.addEventListener('click', (e) => {
        e.preventDefault();
        const direction = button.getAttribute('data-direction');
        this.handleVirtualDirection(direction);
      });
    });
  }

  // 处理虚拟按键方向输入
  handleVirtualDirection(direction) {
    if (!this.gameRunning) {
      this.startGame();
      return;
    }
    
    switch(direction) {
      case 'up':
        if (this.direction.y === 0) this.direction = { x: 0, y: -1 };
        break;
      case 'down':
        if (this.direction.y === 0) this.direction = { x: 0, y: 1 };
        break;
      case 'left':
        if (this.direction.x === 0) this.direction = { x: -1, y: 0 };
        break;
      case 'right':
        if (this.direction.x === 0) this.direction = { x: 1, y: 0 };
        break;
    }
  }

  startShapeTransition(fromRealm, toRealm) {
    // 设置过渡动画状态
    this.shapeTransition = {
      active: true,
      startTime: Date.now(),
      duration: 2000, // 2秒过渡时间
      fromRealmIndex: this.realms.indexOf(fromRealm),
      toRealmIndex: this.realms.indexOf(toRealm),
      progress: 0
    };
    
    // 创建形状变化特效
    this.createShapeTransitionEffects();
  }
  
  createShapeTransitionEffects() {
    // 为蛇的每个身体段创建变形粒子效果
    this.snake.forEach((segment, index) => {
      const centerX = (segment.x + 0.5) * this.cellSize;
      const centerY = (segment.y + 0.5) * this.cellSize;
      
      // 创建变形光环粒子
      for (let i = 0; i < 8; i++) {
        const angle = (i / 8) * Math.PI * 2;
        const radius = this.cellSize * 0.6;
        const particleX = centerX + Math.cos(angle) * radius;
        const particleY = centerY + Math.sin(angle) * radius;
        
        this.particles.push({
          x: particleX,
          y: particleY,
          vx: Math.cos(angle) * 2,
          vy: Math.sin(angle) * 2,
          life: 1.0,
          maxLife: 1.0,
          size: 3,
          color: this.currentRealm.color,
          type: 'shapeTransition',
          delay: index * 50 // 延迟效果，从头到尾依次变化
        });
      }
    });
  }
  
  updateShapeTransition() {
    if (!this.shapeTransition || !this.shapeTransition.active) return;
    
    const elapsed = Date.now() - this.shapeTransition.startTime;
    this.shapeTransition.progress = Math.min(elapsed / this.shapeTransition.duration, 1);
    
    // 使用缓动函数让过渡更自然
    const easeProgress = this.easeInOutCubic(this.shapeTransition.progress);
    
    // 当过渡完成时，清除过渡状态
    if (this.shapeTransition.progress >= 1) {
      this.shapeTransition.active = false;
      this.shapeTransition = null;
    }
  }
  
  easeInOutCubic(t) {
    return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
  }
  
  getTransitionShapeIndex(segmentIndex) {
    if (!this.shapeTransition || !this.shapeTransition.active) {
      return undefined;
    }
    
    const progress = this.shapeTransition.progress;
    const fromIndex = this.shapeTransition.fromRealmIndex;
    const toIndex = this.shapeTransition.toRealmIndex;
    
    // 根据进度在两个形状之间插值
    if (progress < 0.5) {
      return fromIndex;
    } else {
      return toIndex;
    }
  }
  
  loadFoodImages() {
    this.realms.forEach((realm, index) => {
      const img = new Image();
      img.src = `./food/${realm.food}`;
      this.foodImages[realm.name] = img;
    });
  }

  loadHighestRealm() {
    try {
      const saved = localStorage.getItem('immortalSnakeHighestRealm');
      if (saved) {
        const parsed = JSON.parse(saved);
        // 验证解析的对象是否有效
        if (parsed && parsed.name && typeof parsed.threshold === 'number') {
          return parsed;
        }
      }
    } catch (e) {
      console.warn('Failed to load highest realm from localStorage:', e);
    }
    return this.realms[0];
  }

  saveHighestRealm() {
    localStorage.setItem('immortalSnakeHighestRealm', JSON.stringify(this.highestRealm));
  }

  updateHighScoreDisplay() {
    const highScoreElement = document.getElementById('highScore');
    if (highScoreElement && this.highestRealm) {
      highScoreElement.textContent = this.highestRealm.name;
    }
  }
  
  updateDifficultyDisplay() {
    const difficultyValueElement = document.getElementById('difficultyValue');
    if (difficultyValueElement) {
      difficultyValueElement.textContent = this.difficultyNames[this.difficulty];
    }
    // 同时更新境界指南
    this.updateRealmGuide();
  }
  
  updateSpeedDisplay() {
    const speedNames = ['极慢', '较慢', '中等', '较快', '极快'];
    const speedElement = document.getElementById('speedValue');
    if (speedElement) {
      speedElement.textContent = speedNames[this.gameSpeed - 1] || '中等';
    }
  }
  
  updateRealmGuide() {
    const realmItems = document.querySelectorAll('.realm-item .realm-desc');
    if (realmItems.length >= this.realms.length) {
      this.realms.forEach((realm, index) => {
        const currentThreshold = this.getAdjustedThreshold(realm);
        const nextRealm = this.realms[index + 1];
        if (nextRealm) {
          const nextThreshold = this.getAdjustedThreshold(nextRealm);
          realmItems[index].textContent = `${currentThreshold}-${nextThreshold}灵力`;
        } else {
          realmItems[index].textContent = `${currentThreshold}+灵力`;
        }
      });
    }
  }
  
  updateRealmThresholds() {
    // 根据当前难度重新计算境界阈值
    const multiplier = this.difficultyMultipliers[this.difficulty];
    this.realms.forEach((realm, index) => {
      if (index === 0) {
        realm.adjustedThreshold = 0; // 第一个境界始终为0
      } else {
        realm.adjustedThreshold = Math.ceil(realm.threshold * multiplier);
      }
    });
  }
  
  getAdjustedThreshold(realm) {
    if (realm.adjustedThreshold !== undefined) {
      return realm.adjustedThreshold;
    }
    const multiplier = this.difficultyMultipliers[this.difficulty];
    return realm.threshold === 0 ? 0 : Math.ceil(realm.threshold * multiplier);
  }

  setupEventListeners() {
    document.addEventListener('keydown', (e) => {
      if (!this.gameRunning && e.code === 'Space') {
        this.startGame();
        return;
      }
      
      if (this.gameRunning) {
        switch(e.code) {
          case 'ArrowUp':
            if (this.direction.y === 0) this.direction = { x: 0, y: -1 };
            break;
          case 'ArrowDown':
            if (this.direction.y === 0) this.direction = { x: 0, y: 1 };
            break;
          case 'ArrowLeft':
            if (this.direction.x === 0) this.direction = { x: -1, y: 0 };
            break;
          case 'ArrowRight':
            if (this.direction.x === 0) this.direction = { x: 1, y: 0 };
            break;
          case 'KeyA':
            // 灵气护体（被动技能，无需按键激活）
            if (!this.isPaused) {
              this.showSkillNotification('灵气护体是被动技能，筑基期后自动启用');
            }
            break;
          case 'KeyS':
            // 瞬移术
            if (!this.isPaused) {
              this.tryUseSpecificSkill('shunyiShu');
            }
            break;
          case 'KeyD':
            // 元婴化身
            if (!this.isPaused) {
              this.tryUseSpecificSkill('autoXiuxian');
            }
            break;
          case 'KeyF':
            // 龙威震慑
            if (!this.isPaused) {
              this.tryUseSpecificSkill('longweiZhenshe');
            }
            break;
          case 'KeyG':
            // 天道轮回
            if (!this.isPaused) {
              this.tryUseSpecificSkill('tiandaoLunhui');
            }
            break;
          case 'KeyP':
            this.togglePause();
            break;
          case 'KeyQ':
            // 快捷键切换自动修仙模式
            this.toggleAutoPlay();
            break;
        }
      }
    });
    
    document.getElementById('startBtn').addEventListener('click', () => this.startGame());
    document.getElementById('autoPlayBtn').addEventListener('click', () => this.toggleAutoPlay());
    document.getElementById('restartBtn').addEventListener('click', () => this.restart());
    
    // 暂停功能通过空格键实现，不需要单独的暂停按钮
    
    // 难度选择器事件监听
    document.getElementById('difficultySelect').addEventListener('change', (e) => {
      this.difficulty = parseInt(e.target.value);
      this.updateDifficultyDisplay();
      // 如果游戏正在运行，重新计算当前境界阈值
      if (this.gameRunning) {
        this.updateRealmThresholds();
      }
    });
    
    // 修炼速度滑块事件监听
    document.getElementById('speedSlider').addEventListener('input', (e) => {
      this.gameSpeed = parseInt(e.target.value);
      this.updateSpeedDisplay();
    });
    
    // 初始化难度显示
    this.updateDifficultyDisplay();
    // 初始化速度显示
    this.updateSpeedDisplay();
    // 初始化虚拟按键（移动端）
    this.initVirtualControls();
  }
  
  generateFood() {
    let newFood;
    do {
      newFood = {
        x: Math.floor(Math.random() * this.gridWidth),
        y: Math.floor(Math.random() * this.gridHeight)
      };
    } while (this.snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
    return newFood;
  }
  
  startGame() {
    if (!this.gameRunning) {
      this.gameRunning = true;
      this.isPaused = false;
      
      // 初始化难度阈值
      this.updateRealmThresholds();
      
      // 初始化网格缓存
      this.initGridCache();
      
      // 添加游戏开始状态类，显示游戏界面
      document.querySelector('.game-container').classList.add('game-started');
      
      // 设置初始背景
      this.setRealmBackground(this.currentRealm.background);
      
      // 设置初始canvas边框颜色
      this.updateCanvasBorderColor();
      
      // 播放初始境界背景音乐
      this.playRealmAudio(this.currentRealm.audio);
      
      // 播放初始境界视频
      this.playRealmVideo(this.currentRealm.video);
    }
  }
  
  togglePause() {
    if (this.gameRunning) {
      this.isPaused = !this.isPaused;
      if (!this.isPaused) {
        this.gameLoop();
      }
    }
  }
  
  toggleAutoPlay() {
    this.autoPlay = !this.autoPlay;
    const autoBtn = document.getElementById('autoPlayBtn');
    if (this.autoPlay) {
      autoBtn.textContent = '停止自动修仙';
      autoBtn.classList.add('active');
      if (!this.gameRunning) {
        this.startGame();
      }
    } else {
      autoBtn.textContent = '自动修仙';
      autoBtn.classList.remove('active');
    }
  }
   
   autoMove() {
     const head = this.snake[0];
     const food = this.food;
     
     // 计算到食物的方向和距离
     const dx = food.x - head.x;
     const dy = food.y - head.y;
     const foodDistance = Math.abs(dx) + Math.abs(dy);
     
     // 可能的移动方向
     const directions = [
       { x: 0, y: -1, name: 'up' },    // 上
       { x: 0, y: 1, name: 'down' },   // 下
       { x: -1, y: 0, name: 'left' },  // 左
       { x: 1, y: 0, name: 'right' }   // 右
     ];
     
     // 过滤掉反向移动
     const validDirections = directions.filter(dir => 
       !(dir.x === -this.direction.x && dir.y === -this.direction.y)
     );
     
     // 为每个方向计算安全性和优先级
     const scoredDirections = validDirections.map(dir => {
       const newHead = { x: head.x + dir.x, y: head.y + dir.y };
       
       let score = 0;
       
       // 检查是否会撞墙
       if (newHead.x < 0 || newHead.x >= this.gridWidth || 
           newHead.y < 0 || newHead.y >= this.gridHeight) {
         score -= 10000;
       }
       
       // 检查是否会撞到自己
       if (this.snake.some(segment => segment.x === newHead.x && segment.y === newHead.y)) {
         score -= 10000;
       }
       
       // 如果当前方向安全，进行综合分析
       if (score > -10000) {
         // A*路径规划 - 计算到食物的最优路径
         const pathScore = this.calculatePathScore(newHead, food);
         score += pathScore;
         
         // 前瞻性安全检查 - 动态调整深度
         const safetyDepth = foodDistance < 5 ? 2 : 3; // 距离近时减少前瞻深度，提高效率
         const safetyScore = this.calculateSafetyScore(newHead, dir, safetyDepth);
         score += safetyScore * 0.7; // 降低安全权重
         
         // 空间分析 - 根据蛇长度动态调整
         const spaceScore = this.calculateSpaceScore(newHead);
         const spaceWeight = this.snake.length > 10 ? 1.5 : 0.8; // 蛇越长越重视空间
         score += spaceScore * spaceWeight;
         
         // 死胡同检测 - 根据距离调整权重
         const deadEndPenalty = this.calculateDeadEndPenalty(newHead, dir);
         const deadEndWeight = foodDistance === 1 ? 0 : (foodDistance < 3 ? 0.5 : 1.0); // 距离1时忽略死胡同
         score -= deadEndPenalty * deadEndWeight;
         
         // 强化食物追踪 - 多维度评分
         const foodScore = this.calculateFoodScore(newHead, food, dir);
         score += foodScore;
         
         // 紧急食物追踪 - 当距离为1时大幅提升直接朝向食物的分数
         if (foodDistance === 1) {
           const directToFood = (dx > 0 && dir.x > 0) || (dx < 0 && dir.x < 0) || 
                               (dy > 0 && dir.y > 0) || (dy < 0 && dir.y < 0);
           if (directToFood) {
             score += 1000; // 超高优先级确保吃到食物
           }
         }
         
         // 智能惯性 - 根据情况调整
         if (dir.x === this.direction.x && dir.y === this.direction.y) {
           const inertiaBonus = this.isDirectPathToFood(head, food, dir) ? 25 : 10;
           score += inertiaBonus;
         }
         
         // 动态边缘策略
         const edgePenalty = this.calculateEdgePenalty(newHead, food);
         score -= edgePenalty;
         
         // 避免震荡 - 检测来回移动（但在接近食物时优先吃食物）
         if (this.isOscillating(dir) && foodDistance > 2) {
           score -= 50;
         }
       }
       
       return { direction: dir, score };
     });
     
     // 选择得分最高的方向
     scoredDirections.sort((a, b) => b.score - a.score);
     
     // 智能方向选择
     if (scoredDirections.length > 0) {
       const bestDirection = scoredDirections[0];
       
       // 如果最佳方向是安全的，直接选择
       if (bestDirection.score > -10000) {
         this.direction = bestDirection.direction;
       } else {
         // 危险情况下的紧急策略
         const emergencyDirection = this.findEmergencyDirection(validDirections);
         this.direction = emergencyDirection || bestDirection.direction;
       }
     }
     
     // 记录移动历史用于震荡检测
     this.recordMovement(this.direction);
   }
   
   // 计算前瞻性安全分数
   calculateSafetyScore(startPos, direction, depth) {
     if (depth <= 0) return 0;
     
     let safetyScore = 0;
     const nextPos = { x: startPos.x + direction.x, y: startPos.y + direction.y };
     
     // 检查下一步是否安全
     if (nextPos.x < 0 || nextPos.x >= this.gridWidth || 
         nextPos.y < 0 || nextPos.y >= this.gridHeight) {
       return -1000;
     }
     
     if (this.snake.some(segment => segment.x === nextPos.x && segment.y === nextPos.y)) {
       return -1000;
     }
     
     safetyScore += 100; // 基础安全分
     
     // 递归检查更深层的安全性
     const futureDirections = [
       { x: 0, y: -1 }, { x: 0, y: 1 }, { x: -1, y: 0 }, { x: 1, y: 0 }
     ].filter(dir => !(dir.x === -direction.x && dir.y === -direction.y));
     
     let maxFutureSafety = -1000;
     for (const futureDir of futureDirections) {
       const futureSafety = this.calculateSafetyScore(nextPos, futureDir, depth - 1);
       maxFutureSafety = Math.max(maxFutureSafety, futureSafety);
     }
     
     return safetyScore + maxFutureSafety * 0.5;
   }
   
   // 计算周围空间分数
   calculateSpaceScore(pos) {
     let spaceCount = 0;
     const checkRadius = 2;
     
     for (let dx = -checkRadius; dx <= checkRadius; dx++) {
       for (let dy = -checkRadius; dy <= checkRadius; dy++) {
         const checkX = pos.x + dx;
         const checkY = pos.y + dy;
         
         if (checkX >= 0 && checkX < this.gridWidth && 
             checkY >= 0 && checkY < this.gridHeight) {
           if (!this.snake.some(segment => segment.x === checkX && segment.y === checkY)) {
             spaceCount++;
           }
         }
       }
     }
     
     return spaceCount * 2; // 空间越大分数越高
   }
   
   // 计算死胡同惩罚
    calculateDeadEndPenalty(pos, direction) {
      const futurePos = { x: pos.x + direction.x, y: pos.y + direction.y };
      
      // 检查是否会进入死胡同
      let exitCount = 0;
      const directions = [
        { x: 0, y: -1 }, { x: 0, y: 1 }, { x: -1, y: 0 }, { x: 1, y: 0 }
      ];
      
      for (const dir of directions) {
        const exitX = futurePos.x + dir.x;
        const exitY = futurePos.y + dir.y;
        
        if (exitX >= 0 && exitX < this.gridWidth && 
            exitY >= 0 && exitY < this.gridHeight) {
          if (!this.snake.some(segment => segment.x === exitX && segment.y === exitY)) {
            exitCount++;
          }
        }
      }
      
      // 如果出口太少，增加惩罚
      if (exitCount <= 1) {
        return 500; // 高惩罚
      } else if (exitCount <= 2) {
        return 100; // 中等惩罚
      }
      
      return 0; // 无惩罚
    }
    
    // A*路径规划算法
    calculatePathScore(start, target) {
      const dx = target.x - start.x;
      const dy = target.y - start.y;
      const distance = Math.abs(dx) + Math.abs(dy);
      
      // 基础路径分数（距离越近分数越高）
      let pathScore = Math.max(0, 100 - distance * 2);
      
      // 直线路径奖励
      if (dx === 0 || dy === 0) {
        pathScore += 30; // 直线路径更高效
      }
      
      // 检查路径上是否有障碍
      const pathClear = this.isPathClear(start, target);
      if (pathClear) {
        pathScore += 50; // 路径畅通奖励
      }
      
      return pathScore;
    }
    
    // 检查路径是否畅通
    isPathClear(start, target) {
      const dx = target.x - start.x;
      const dy = target.y - start.y;
      const steps = Math.max(Math.abs(dx), Math.abs(dy));
      
      if (steps === 0) return true;
      
      const stepX = dx / steps;
      const stepY = dy / steps;
      
      for (let i = 1; i < steps; i++) {
        const checkX = Math.round(start.x + stepX * i);
        const checkY = Math.round(start.y + stepY * i);
        
        if (this.snake.some(segment => segment.x === checkX && segment.y === checkY)) {
          return false;
        }
      }
      
      return true;
    }
    
    // 强化食物追踪评分
    calculateFoodScore(pos, food, direction) {
      const dx = food.x - pos.x;
      const dy = food.y - pos.y;
      const distance = Math.abs(dx) + Math.abs(dy);
      
      let foodScore = 0;
      
      // 方向正确性奖励（大幅提升）
      if ((dx > 0 && direction.x > 0) || (dx < 0 && direction.x < 0)) {
        foodScore += Math.abs(dx) * 15; // 提高X方向权重
      }
      if ((dy > 0 && direction.y > 0) || (dy < 0 && direction.y < 0)) {
        foodScore += Math.abs(dy) * 15; // 提高Y方向权重
      }
      
      // 距离奖励（距离越近奖励越高）
      foodScore += Math.max(0, 50 - distance * 3);
      
      // 最优方向奖励
      if (this.isOptimalDirection(pos, food, direction)) {
        foodScore += 40;
      }
      
      return foodScore;
    }
    
    // 判断是否为最优方向
    isOptimalDirection(pos, food, direction) {
      const dx = food.x - pos.x;
      const dy = food.y - pos.y;
      
      // 如果只需要在一个轴上移动
      if (dx === 0) return direction.y === Math.sign(dy);
      if (dy === 0) return direction.x === Math.sign(dx);
      
      // 选择距离更远的轴作为优先方向
      if (Math.abs(dx) > Math.abs(dy)) {
        return direction.x === Math.sign(dx);
      } else {
        return direction.y === Math.sign(dy);
      }
    }
    
    // 检查是否有直接路径到食物
    isDirectPathToFood(pos, food, direction) {
      const dx = food.x - pos.x;
      const dy = food.y - pos.y;
      
      // 检查当前方向是否直接指向食物
      return (dx > 0 && direction.x > 0) || (dx < 0 && direction.x < 0) ||
             (dy > 0 && direction.y > 0) || (dy < 0 && direction.y < 0);
    }
    
    // 动态边缘惩罚
    calculateEdgePenalty(pos, food) {
      const edgeDistance = Math.min(pos.x, pos.y, this.gridWidth - 1 - pos.x, this.gridHeight - 1 - pos.y);
      
      // 如果食物在边缘附近，降低边缘惩罚
      const foodEdgeDistance = Math.min(food.x, food.y, this.gridWidth - 1 - food.x, this.gridHeight - 1 - food.y);
      
      if (foodEdgeDistance <= 2) {
        return edgeDistance <= 1 ? 5 : 0; // 食物在边缘时降低惩罚
      }
      
      return edgeDistance <= 1 ? 30 : (edgeDistance <= 2 ? 10 : 0);
    }
    
    // 震荡检测
    isOscillating(direction) {
      if (!this.moveHistory) {
        this.moveHistory = [];
      }
      
      // 检查最近4步是否有来回移动
      if (this.moveHistory.length >= 3) {
        const recent = this.moveHistory.slice(-3);
        const current = direction;
        
        // 检测ABAB模式
        if (recent.length >= 2) {
          const prev1 = recent[recent.length - 1];
          const prev2 = recent[recent.length - 2];
          
          return (current.x === prev2.x && current.y === prev2.y) &&
                 (prev1.x === -current.x && prev1.y === -current.y);
        }
      }
      
      return false;
    }
    
    // 记录移动历史
    recordMovement(direction) {
      if (!this.moveHistory) {
        this.moveHistory = [];
      }
      
      this.moveHistory.push({ x: direction.x, y: direction.y });
      
      // 只保留最近10步
      if (this.moveHistory.length > 10) {
        this.moveHistory.shift();
      }
    }
    
    // 紧急方向查找
    findEmergencyDirection(validDirections) {
      // 寻找能延长生存时间最长的方向
      let bestDirection = null;
      let maxSurvivalSteps = 0;
      
      for (const dir of validDirections) {
        const survivalSteps = this.calculateSurvivalSteps(dir, 5);
        if (survivalSteps > maxSurvivalSteps) {
          maxSurvivalSteps = survivalSteps;
          bestDirection = dir;
        }
      }
      
      return bestDirection;
    }
    
    // 计算生存步数
    calculateSurvivalSteps(direction, maxSteps) {
      const head = this.snake[0];
      let currentPos = { x: head.x + direction.x, y: head.y + direction.y };
      let steps = 0;
      
      for (let i = 0; i < maxSteps; i++) {
        // 检查是否撞墙或撞自己
        if (currentPos.x < 0 || currentPos.x >= this.gridWidth ||
            currentPos.y < 0 || currentPos.y >= this.gridHeight ||
            this.snake.some(segment => segment.x === currentPos.x && segment.y === currentPos.y)) {
          break;
        }
        
        steps++;
        // 继续沿当前方向移动
        currentPos.x += direction.x;
        currentPos.y += direction.y;
      }
      
      return steps;
    }
   
   restart() {
      this.snake = [{ x: 10, y: 10 }, { x: 9, y: 10 }]; // 默认长度为2
      this.direction = { x: 1, y: 0 };
      this.food = this.generateFood();
      this.score = 0;
      this.spirit = 0; // 重置灵力值
      this.currentRealm = this.realms[0];
      this.gameRunning = false;
      this.isPaused = false;
      this.autoPlay = false;
      
      // 清空所有粒子特效
      this.particles = [];
      
      // 移除游戏开始状态类，回到初始界面
      document.querySelector('.game-container').classList.remove('game-started');
      
      // 停止背景音乐
      this.stopRealmAudio();
      
      // 重置背景
      const body = document.body;
      body.style.backgroundImage = '';
      body.classList.remove('has-background');
      
      // 重置按钮状态
      const autoBtn = document.getElementById('autoPlayBtn');
      autoBtn.textContent = '自动修仙';
      autoBtn.classList.remove('active');
      
      // 重置技能系统
      this.resetSkills();
      
      this.updateUI();
    this.draw();
  }

  // 重置技能系统
  resetSkills() {
    // 重置所有技能状态
    Object.keys(this.skills).forEach(skillKey => {
      const skill = this.skills[skillKey];
      skill.lastUsed = 0;
      // 被动技能不重置active状态
      if (!skill.passive) {
        skill.active = false;
      }
      skill.activatedAt = 0;
      if (skillKey === 'tiandaoLunhui') {
        skill.used = false;
      }
    });
    
    // 重置技能效果状态
    this.skillEffects.timeSlowFactor = 1.0;
    // 灵气护体是被动技能，不重置无敌状态
    // this.skillEffects.invulnerable = false;
  }

  // 尝试使用技能
  tryUseSkill() {
    const currentTime = Date.now();
    const currentRealmIndex = this.realms.indexOf(this.currentRealm);
    
    // 根据当前境界确定可用技能
    let availableSkill = null;
    
    // 从高级技能开始检查（优先使用高级技能）
    const skillKeys = ['tiandaoLunhui', 'longweiZhenshe', 'autoXiuxian', 'shunyiShu', 'lingqiHuti'];
    
    for (const skillKey of skillKeys) {
      const skill = this.skills[skillKey];
      if (currentRealmIndex >= skill.realmIndex) {
        // 检查冷却时间
        if (currentTime - skill.lastUsed >= skill.cooldown) {
          // 检查特殊条件
          if (skillKey === 'tiandaoLunhui' && skill.used) {
            continue; // 天道轮回每局只能用一次
          }
          availableSkill = { key: skillKey, skill: skill };
          break;
        }
      }
    }
    
    if (availableSkill) {
      this.activateSkill(availableSkill.key, availableSkill.skill);
    }
  }

  // 尝试使用特定技能
  tryUseSpecificSkill(skillKey) {
    const currentTime = Date.now();
    const skill = this.skills[skillKey];
    
    if (!skill) return;
    
    // 检查境界要求
    const currentRealmIndex = this.realms.findIndex(realm => realm.name === this.currentRealm.name);
    const realmRequirements = {
      'lingqi': 1,    // 筑基期
      'shunyi': 2,    // 金丹期
      'autoXiuxian': 3,   // 元婴期
      'longwei': 4,   // 化神期
      'tiandao': 5    // 飞升期
    };
    const requiredRealmIndex = realmRequirements[skillKey];
    
    if (currentRealmIndex < requiredRealmIndex) {
      const requiredRealmName = this.realms[requiredRealmIndex]?.name || '未知境界';
      this.showSkillNotification(`需要达到${requiredRealmName}才能使用此技能`);
      return;
    }
    
    // 检查冷却时间
    if (skill.lastUsed && currentTime - skill.lastUsed < skill.cooldown) {
      const remainingTime = Math.ceil((skill.cooldown - (currentTime - skill.lastUsed)) / 1000);
      this.showSkillNotification(`技能冷却中，还需${remainingTime}秒`);
      return;
    }
    
    // 检查天道轮回的特殊限制
    if (skillKey === 'tiandaoLunhui' && skill.used) {
      this.showSkillNotification('天道轮回每局只能使用一次');
      return;
    }
    
    // 激活技能
    this.activateSkill(skillKey, skill);
  }

  // 激活技能
  activateSkill(skillKey, skill) {
    const currentTime = Date.now();
    skill.lastUsed = currentTime;
    
    switch (skillKey) {
      case 'lingqiHuti':
        // 灵气护体是被动技能，无需主动激活
        this.showSkillNotification('灵气护体已是被动技能');
        return;
      case 'shunyiShu':
        this.activateShunyiShu(skill);
        break;
      case 'autoXiuxian':
        this.activateAutoXiuxian(skill);
        return; // 元婴化身方法内部已经处理了通知，直接返回
      case 'longweiZhenshe':
        this.activateLongweiZhenshe(skill);
        break;
      case 'tiandaoLunhui':
        // 天道轮回是被动技能，在死亡时触发
        skill.used = true;
        break;
    }
    
    // 显示技能激活提示
    this.showSkillNotification(skill.name);
  }

  // 更新技能状态
  updateSkills() {
    const currentTime = Date.now();
    
    // 灵气护体现在是被动技能，无需更新状态
    
    // 元婴化身现在是立即生效，无需持续更新
    
    // 更新龙威震慑
    if (this.skills.longweiZhenshe.active) {
      if (currentTime - this.skills.longweiZhenshe.activatedAt >= this.skills.longweiZhenshe.duration) {
        this.skills.longweiZhenshe.active = false;
        this.skillEffects.timeSlowFactor = 1.0;
      }
    }
    
    // 更新技能UI
    this.updateSkillUI();
  }

  // 更新技能UI界面
  updateSkillUI() {
    const currentRealmIndex = this.realms.findIndex(realm => realm.name === this.currentRealm.name);
    const currentTime = Date.now();
    
    // 技能映射
    const skillMapping = {
      'lingqi': 'lingqiHuti',
      'shunyi': 'shunyiShu', 
      'fenshen': 'autoXiuxian',
      'longwei': 'longweiZhenshe',
      'tiandao': 'tiandaoLunhui'
    };
    
    // 境界要求映射
    const realmRequirements = {
        'lingqi': 1,    // 筑基期
        'shunyi': 2,    // 金丹期
        'fenshen': 3,   // 元婴期
        'longwei': 4,   // 化神期
        'tiandao': 5    // 飞升期
      };
    
    for (let skillKey in skillMapping) {
      const skillName = skillMapping[skillKey];
      const skill = this.skills[skillName];
      const skillElement = document.getElementById(`skill-${skillKey}`);
      const cooldownElement = document.getElementById(`cooldown-${skillKey}`);
      const overlayElement = document.getElementById(`overlay-${skillKey}`);
      
      if (!skillElement || !skill) continue;
      
      // 检查技能是否可用（境界要求 - 高境界可使用低境界技能）
      const requiredRealmIndex = realmRequirements[skillKey];
      const isRealmUnlocked = currentRealmIndex >= requiredRealmIndex;
      
      // 检查冷却状态
      const timeSinceLastUse = currentTime - (skill.lastUsed || 0);
      const isOnCooldown = timeSinceLastUse < skill.cooldown;
      
      // 检查特殊限制（如天道轮回的单次使用）
      const isUsed = skill.used || false;
      
      // 更新技能项样式
      skillElement.classList.remove('available', 'unavailable', 'cooldown');
      
      // 特殊处理灵气护体被动技能
      if (skillKey === 'lingqi' && skill.passive) {
        if (!isRealmUnlocked) {
          skillElement.classList.add('unavailable');
          cooldownElement.textContent = '未解锁';
          cooldownElement.className = 'skill-cooldown';
        } else {
          skillElement.classList.add('available');
          cooldownElement.textContent = '被动';
          cooldownElement.className = 'skill-cooldown passive';
          // 清除冷却遮罩
          if (overlayElement) {
            overlayElement.style.background = '';
          }
        }
      } else if (!isRealmUnlocked) {
        skillElement.classList.add('unavailable');
        cooldownElement.textContent = '未解锁';
        cooldownElement.className = 'skill-cooldown';
      } else if (isUsed && skillKey === 'tiandao') {
        skillElement.classList.add('unavailable');
        cooldownElement.textContent = '已使用';
        cooldownElement.className = 'skill-cooldown';
      } else if (isOnCooldown) {
        skillElement.classList.add('cooldown');
        const remainingTime = skill.cooldown - timeSinceLastUse;
        const remainingSeconds = Math.ceil(remainingTime / 1000);
        cooldownElement.textContent = `${remainingSeconds}s`;
        cooldownElement.className = 'skill-cooldown cooling';
        
        // 更新冷却遮罩
        if (overlayElement) {
          const progress = timeSinceLastUse / skill.cooldown;
          overlayElement.style.background = `conic-gradient(transparent ${progress * 360}deg, rgba(0,0,0,0.7) 0deg)`;
        }
      } else {
        skillElement.classList.add('available');
        cooldownElement.textContent = '就绪';
        cooldownElement.className = 'skill-cooldown ready';
        
        // 清除冷却遮罩
        if (overlayElement) {
          overlayElement.style.background = '';
        }
      }
    }
  }

  gameLoop() {
    if (!this.gameRunning || this.isPaused) return;
    
    this.update();
    this.updateParticles();
    this.createTrailParticles();
    this.draw();
    
    // 应用时间减速效果
    const adjustedSpeed = this.gameSpeed / this.skillEffects.timeSlowFactor;
    setTimeout(() => this.gameLoop(), adjustedSpeed);
  }

  // 激活灵气护体
  activateLingqiHuti(skill) {
    skill.active = true;
    skill.activatedAt = Date.now();
    skill.lastUsed = Date.now();
    this.skillEffects.invulnerable = true;
    this.showSkillNotification('灵气护体');
  }

  // 激活瞬移术
  activateShunyiShu(skill) {
    skill.lastUsed = Date.now();
    
    // 寻找安全位置进行瞬移
    const safePositions = [];
    
    for (let x = 1; x < this.gridWidth - 1; x++) {
      for (let y = 1; y < this.gridHeight - 1; y++) {
        // 检查位置是否安全（不与蛇身重叠，不在边界）
        const isSafe = !this.snake.some(segment => segment.x === x && segment.y === y) &&
                      !this.isNearSnake(x, y, 2); // 距离蛇身至少2格
        
        if (isSafe) {
          safePositions.push({ x, y });
        }
      }
    }
    
    if (safePositions.length > 0) {
      const randomPos = safePositions[Math.floor(Math.random() * safePositions.length)];
      this.snake[0] = { x: randomPos.x, y: randomPos.y };
      
      // 创建瞬移特效
      this.createTeleportEffect(randomPos.x, randomPos.y);
      this.showSkillNotification('瞬移术');
    }
  }

  // 激活元婴化身
  activateAutoXiuxian(skill) {
    skill.lastUsed = Date.now();
    
    // 增加修为（score）和灵力
    const scoreGain = 2; // 增加2点修为
    this.score += scoreGain;
    this.spirit += skill.spiritGain;
    
    // 蛇身体增长（模拟吃到食物的效果）
    const head = this.snake[0];
    this.snake.push({ x: head.x, y: head.y }); // 在尾部添加一节
    
    // 检查境界突破
    this.checkRealmBreakthrough();
    
    this.updateUI(); // 更新UI显示
    this.showSkillNotification(`元婴化身 +${scoreGain}修为 +${skill.spiritGain}灵力`);
  }

  // 激活龙威震慑
  activateLongweiZhenshe(skill) {
    skill.active = true;
    skill.activatedAt = Date.now();
    skill.lastUsed = Date.now();
    this.skillEffects.timeSlowFactor = 0.5; // 时间减速50%
    
    // 创建龙威特效
    this.createDragonAuraEffect();
    this.showSkillNotification('龙威震慑');
  }

  // 检查位置是否靠近蛇身
  isNearSnake(x, y, distance) {
    return this.snake.some(segment => {
      const dx = Math.abs(segment.x - x);
      const dy = Math.abs(segment.y - y);
      return dx <= distance && dy <= distance;
    });
  }

  // 创建瞬移特效
  createTeleportEffect(x, y) {
    const centerX = (x + 0.5) * this.cellSize;
    const centerY = (y + 0.5) * this.cellSize;
    
    // 创建金色传送粒子
    for (let i = 0; i < 20; i++) {
      const angle = (i / 20) * Math.PI * 2;
      const radius = this.cellSize * 2;
      const particleX = centerX + Math.cos(angle) * radius;
      const particleY = centerY + Math.sin(angle) * radius;
      
      this.particles.push({
        x: particleX,
        y: particleY,
        vx: Math.cos(angle) * -3,
        vy: Math.sin(angle) * -3,
        life: 1.0,
        decay: 0.05,
        color: '#FFD700',
        size: 4,
        type: 'teleport'
      });
    }
  }

  // 创建龙威特效
  createDragonAuraEffect() {
    // 在屏幕边缘创建龙纹特效粒子
    const edges = [
      { x: 0, y: 0, width: this.canvas.width, height: 10 }, // 上边
      { x: 0, y: this.canvas.height - 10, width: this.canvas.width, height: 10 }, // 下边
      { x: 0, y: 0, width: 10, height: this.canvas.height }, // 左边
      { x: this.canvas.width - 10, y: 0, width: 10, height: this.canvas.height } // 右边
    ];
    
    edges.forEach(edge => {
      for (let i = 0; i < 30; i++) {
        this.particles.push({
          x: edge.x + Math.random() * edge.width,
          y: edge.y + Math.random() * edge.height,
          vx: (Math.random() - 0.5) * 2,
          vy: (Math.random() - 0.5) * 2,
          life: 1.0,
          decay: 0.02,
          color: '#FF6347',
          size: 6,
          type: 'dragonAura'
        });
      }
    });
  }

  // 显示技能激活通知
  showSkillNotification(skillName) {
    const notification = document.createElement('div');
    notification.className = 'skill-notification';
    notification.textContent = `${skillName} 激活！`;
    notification.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: linear-gradient(45deg, #FFD700, #FF6347);
      color: white;
      padding: 15px 30px;
      border-radius: 10px;
      font-size: 24px;
      font-weight: bold;
      text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
      box-shadow: 0 0 20px rgba(255, 215, 0, 0.5);
      z-index: 1000;
      animation: skillNotification 2s ease-out forwards;
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
      if (notification.parentNode) {
        notification.parentNode.removeChild(notification);
      }
    }, 2000);
  }

  // 天道轮回技能激活
  activateTiandaoLunhui(skill) {
    skill.used = true; // 标记为已使用，每局游戏只能用一次
    
    // 创建凤凰涅槃特效
    this.createPhoenixRebornEffect();
    
    // 显示技能通知
    this.showSkillNotification('天道轮回');
    
    // 重置蛇的位置到中心，保持当前长度
    const centerX = Math.floor(this.gridWidth / 2);
    const centerY = Math.floor(this.gridHeight / 2);
    
    // 保持蛇的当前长度，重新排列在中心位置
    const currentLength = this.snake.length;
    this.snake = [];
    for (let i = 0; i < currentLength; i++) {
      this.snake.push({ x: centerX, y: centerY + i });
    }
    
    // 重置方向为向上
    this.direction = { x: 0, y: -1 };
    
    // 给予短暂的无敌时间
    this.skillEffects.invulnerable = true;
    setTimeout(() => {
      this.skillEffects.invulnerable = false;
    }, 3000); // 3秒无敌时间
    
    // 继续游戏
    this.gameRunning = true;
  }

  // 创建凤凰涅槃特效
  createPhoenixRebornEffect() {
    const centerX = this.canvas.width / 2;
    const centerY = this.canvas.height / 2;
    
    // 创建凤凰火焰粒子
    const colors = ['#FF4500', '#FF6347', '#FFD700', '#FF69B4', '#FF1493'];
    
    for (let i = 0; i < 100; i++) {
      const angle = (Math.PI * 2 * i) / 100;
      const radius = 50 + Math.random() * 100;
      
      this.particles.push({
        x: centerX + Math.cos(angle) * radius,
        y: centerY + Math.sin(angle) * radius,
        vx: Math.cos(angle) * (2 + Math.random() * 3),
        vy: Math.sin(angle) * (2 + Math.random() * 3) - 1, // 向上飘动
        life: 1,
        decay: 0.01,
        color: colors[Math.floor(Math.random() * colors.length)],
        size: 3 + Math.random() * 5
      });
    }
    
    // 创建中心爆炸效果
    for (let i = 0; i < 50; i++) {
      this.particles.push({
        x: centerX,
        y: centerY,
        vx: (Math.random() - 0.5) * 10,
        vy: (Math.random() - 0.5) * 10,
        life: 1,
        decay: 0.02,
        color: '#FFFFFF',
        size: 2 + Math.random() * 4
      });
    }
  }

  update() {
    // 自动修仙AI逻辑
    if (this.autoPlay) {
      this.autoMove();
    }
    
    // 检查灵气护体被动技能状态（筑基期后自动启用）
    const currentRealmIndex = this.realms.findIndex(realm => realm.name === this.currentRealm.name);
    const hasLingqiHuti = currentRealmIndex >= 1; // 筑基期及以上
    if (hasLingqiHuti) {
      this.skillEffects.invulnerable = true;
    }
    
    const head = { ...this.snake[0] };
    head.x += this.direction.x;
    head.y += this.direction.y;
    
    // 检查边界碰撞
    if (head.x < 0 || head.x >= this.gridWidth || head.y < 0 || head.y >= this.gridHeight) {
      if (!this.skillEffects.invulnerable) {
        this.gameOver();
        return;
      } else {
        // 灵气护体状态下，反弹到对面边界（穿墙效果）
        if (head.x < 0) head.x = this.gridWidth - 1;
        if (head.x >= this.gridWidth) head.x = 0;
        if (head.y < 0) head.y = this.gridHeight - 1;
        if (head.y >= this.gridHeight) head.y = 0;
      }
    }

    // 检查自身碰撞（灵气护体只能穿墙，不能穿过身体）
    if (this.snake.some(segment => segment.x === head.x && segment.y === head.y)) {
      this.gameOver();
      return;
    }
    
    this.snake.unshift(head);
    
    // 检查食物碰撞
    if (head.x === this.food.x && head.y === this.food.y) {
      this.score++;
      this.spirit++; // 吃食物增加1点灵力
      this.food = this.generateFood();
      this.checkRealmBreakthrough();
    } else {
      this.snake.pop();
    }
    
    // 更新形状过渡动画
    this.updateShapeTransition();
    
    // 更新技能状态
    this.updateSkills();
    
    this.updateUI();
  }
  
  checkRealmBreakthrough() {
    for (let i = this.realms.length - 1; i >= 0; i--) {
      const adjustedThreshold = this.getAdjustedThreshold(this.realms[i]);
      if (this.score >= adjustedThreshold) {
        if (this.currentRealm !== this.realms[i]) {
          const previousRealm = this.currentRealm;
          this.currentRealm = this.realms[i];
          
          // 启动形状变化过渡动画
          this.startShapeTransition(previousRealm, this.currentRealm);
          
          this.showRealmNotification(this.currentRealm.name);
          this.setRealmBackground(this.currentRealm.background);
          this.playRealmAudio(this.currentRealm.audio);
          this.playRealmVideo(this.currentRealm.video);
          
          // 更新canvas边框颜色为当前境界主题色
          this.updateCanvasBorderColor();
          
          // 实时更新最高境界记录
          if (this.currentRealm.threshold > this.highestRealm.threshold) {
            this.highestRealm = this.currentRealm;
            this.saveHighestRealm();
            this.updateHighScoreDisplay();
          }
        }
        break;
      }
    }
  }
  
  setRealmBackground(backgroundImage) {
    const body = document.body;
    body.style.backgroundImage = `url('./background/${backgroundImage}')`;
    body.classList.add('has-background');
  }
  
  // 更新canvas边框颜色为当前境界主题色
  updateCanvasBorderColor() {
    const canvas = document.getElementById('gameCanvas');
    const themeColor = this.currentRealm.color;
    
    // 动态设置边框颜色和阴影效果
    canvas.style.border = `3px solid ${themeColor}`;
    canvas.style.boxShadow = `
      0 0 20px ${themeColor}50,
      inset 0 0 50px ${themeColor}20
    `;
  }
  
  playRealmAudio(audioFile) {
    // 停止当前播放的音乐
    if (this.currentAudio) {
      this.currentAudio.pause();
      this.currentAudio.currentTime = 0;
    }
    
    // 创建新的音频元素
    this.currentAudio = new Audio(`./audio/${audioFile}`);
    this.currentAudio.loop = true; // 循环播放
    this.currentAudio.volume = 0.3; // 设置音量为30%
    
    // 播放音乐
    this.currentAudio.play().catch(error => {
      console.error('背景音乐播放失败:', error);
    });
  }
  
  stopRealmAudio() {
    if (this.currentAudio) {
      this.currentAudio.pause();
      this.currentAudio.currentTime = 0;
      this.currentAudio = null;
    }
  }
  
  playRealmVideo(videoFile) {
    // 暂停游戏
    const wasRunning = this.gameRunning;
    this.gameRunning = false;
    
    // 创建视频元素
    const video = document.createElement('video');
    video.src = `./video/${videoFile}`;
    video.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      object-fit: cover;
      z-index: 9999;
      background: #000;
    `;
    
    // 创建文字提示覆盖层
    const textOverlay = document.createElement('div');
    textOverlay.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 10000;
      text-align: center;
      color: #FFD700;
      font-family: '华文仿宋', 'STFangsong', 'serif', 'Arial', sans-serif;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8), 0 0 20px rgba(255, 215, 0, 0.6);
      pointer-events: none;
      animation: realmBreakthroughText 3s ease-in-out;
    `;
    
    // 根据境界生成独特的恭喜文案
    const realmMessages = {
      '凡蛇期': {
        title: '🐍 初入修仙 🐍',
        subtitle: '踏上修仙之路',
        description: '凡蛇觉醒，灵智初开！'
      },
      '筑基期': {
        title: '⚡ 筑基成功 ⚡',
        subtitle: '突破至筑基期',
        description: '根基稳固，灵力涌动！'
      },
      '金丹期': {
        title: '💎 金丹凝聚 💎',
        subtitle: '踏入金丹期',
        description: '丹成九转，金光万丈！'
      },
      '元婴期': {
        title: '👶 元婴诞生 👶',
        subtitle: '进阶元婴期',
        description: '元婴出世，神通初显！'
      },
      '化神期': {
        title: '🔥 化神通天 🔥',
        subtitle: '登临化神期',
        description: '神魂蜕变，法力无边！'
      },
      '飞升期': {
        title: '🐉 飞升成龙 🐉',
        subtitle: '证道飞升期',
        description: '化龙飞升，傲视九天！'
      }
    };
    
    const message = realmMessages[this.currentRealm.name] || realmMessages['凡蛇期'];
    
    textOverlay.innerHTML = `
      <div style="font-size: 3em; font-weight: bold; margin-bottom: 20px;">${message.title}</div>
      <div style="font-size: 2.5em; color: ${this.currentRealm.color};">${message.subtitle}</div>
      <div style="font-size: 4em; font-weight: bold; margin: 10px 0; color: ${this.currentRealm.color};">${this.currentRealm.name}</div>
      <div style="font-size: 1.8em; color: #FFF;">${message.description}</div>
    `;
    
    // 添加到页面
    document.body.appendChild(video);
    document.body.appendChild(textOverlay);
    
    // 播放视频
    video.play().then(() => {
      // 3秒后停止播放并移除视频和文字
      setTimeout(() => {
        video.pause();
        document.body.removeChild(video);
        document.body.removeChild(textOverlay);
        
        // 恢复游戏
        if (wasRunning) {
          this.gameRunning = true;
          this.gameLoop();
        }
      }, 3000);
    }).catch(error => {
      console.error('视频播放失败:', error);
      // 如果视频播放失败，直接移除并恢复游戏
      document.body.removeChild(video);
      document.body.removeChild(textOverlay);
      if (wasRunning) {
        this.gameRunning = true;
        this.gameLoop();
      }
    });
  }
  
  showRealmNotification(realmName) {
    const notification = document.createElement('div');
    notification.className = 'realm-notification';
    notification.textContent = `突破至 ${realmName}！`;
    notification.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: linear-gradient(45deg, #FFD700, #FFA500);
      color: #000;
      padding: 20px 40px;
      border-radius: 10px;
      font-size: 24px;
      font-weight: bold;
      z-index: 1000;
      animation: realmBreakthrough 3s ease-out forwards;
    `;
    
    document.body.appendChild(notification);
    setTimeout(() => notification.remove(), 3000);
  }
  
  updateUI() {
    document.getElementById('score').textContent = this.spirit;
    document.getElementById('currentRealm').textContent = this.currentRealm.name;
    
    // 更新经验条 - 使用调整后的阈值
    const nextRealm = this.realms.find(realm => this.getAdjustedThreshold(realm) > this.score);
    if (nextRealm) {
      const currentThreshold = this.getAdjustedThreshold(this.currentRealm);
      const nextThreshold = this.getAdjustedThreshold(nextRealm);
      const progress = ((this.score - currentThreshold) / (nextThreshold - currentThreshold)) * 100;
      document.getElementById('expFill').style.width = Math.max(0, Math.min(100, progress)) + '%';
      document.getElementById('expText').textContent = `${this.score}/${nextThreshold}`;
    } else {
      // 已达到最高境界
      document.getElementById('expFill').style.width = '100%';
      document.getElementById('expText').textContent = `${this.score}/∞`;
    }
  }
  
  gameOver() {
    // 检查天道轮回技能
    const tiandaoSkill = this.skills.tiandaoLunhui;
    if (tiandaoSkill && !tiandaoSkill.used && this.currentRealm.name === '飞升期') {
      this.activateTiandaoLunhui(tiandaoSkill);
      return; // 复活成功，不执行游戏结束逻辑
    }
    
    this.gameRunning = false;
    
    // 停止自动修仙模式
    if (this.autoPlay) {
      this.autoPlay = false;
      const autoBtn = document.getElementById('autoPlayBtn');
      autoBtn.textContent = '自动修仙';
      autoBtn.classList.remove('active');
    }
    
    // 停止背景音乐
    this.stopRealmAudio();
    
    // 检查并更新最高境界
    if (this.currentRealm.threshold > this.highestRealm.threshold) {
      this.highestRealm = this.currentRealm;
      this.saveHighestRealm();
      this.updateHighScoreDisplay();
    }
    
    // 显示游戏结束信息
    alert(`游戏结束！最终得分: ${this.score}\n当前境界: ${this.currentRealm.name}\n最高境界: ${this.highestRealm.name}`);
    
    // 重置游戏状态
    this.restart();
  }
  
  draw() {
    // 清空画布，使用透明背景
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    
    // 绘制网格
    this.drawGrid();
    
    // 绘制粒子
    this.drawParticles();
    
    // 绘制食物
    this.drawFood();
    
    // 绘制蛇
    this.drawSnake();
  }
  
  initGridCache() {
    if (!this.gridCacheCanvas) {
      this.gridCacheCanvas = document.createElement('canvas');
      this.gridCacheCanvas.width = this.canvas.width;
      this.gridCacheCanvas.height = this.canvas.height;
      this.gridCacheCtx = this.gridCacheCanvas.getContext('2d');
    }
  }
  
  cacheGridForRealm(realmName) {
    this.initGridCache();
    
    const realmIndex = this.realms.findIndex(realm => realm.name === realmName);
    const gridThemes = {
      0: { primary: '#40E0D0', secondary: '#20B2AA', glow: '#7FFFD4' },
      1: { primary: '#1E90FF', secondary: '#4169E1', glow: '#87CEEB' },
      2: { primary: '#FFD700', secondary: '#FFA500', glow: '#FFFF99' },
      3: { primary: '#9932CC', secondary: '#8A2BE2', glow: '#DDA0DD' },
      4: { primary: '#FF6347', secondary: '#DC143C', glow: '#FFA07A' },
      5: { primary: '#F5F5DC', secondary: '#DCDCDC', glow: '#FFFACD' }
    };
    
    const theme = gridThemes[realmIndex] || gridThemes[0];
    
    // 清空缓存画布
    this.gridCacheCtx.clearRect(0, 0, this.gridCacheCanvas.width, this.gridCacheCanvas.height);
    this.gridCacheCtx.save();
    
    // 绘制次网格线（细线）到缓存
    this.gridCacheCtx.globalAlpha = 0.2;
    this.gridCacheCtx.strokeStyle = theme.secondary;
    this.gridCacheCtx.lineWidth = 0.5;
    this.gridCacheCtx.shadowColor = theme.glow;
    this.gridCacheCtx.shadowBlur = 1;
    
    this.gridCacheCtx.beginPath();
    for (let x = 0; x <= this.gridWidth; x++) {
      this.gridCacheCtx.moveTo(x * this.cellSize, 0);
      this.gridCacheCtx.lineTo(x * this.cellSize, this.gridCacheCanvas.height);
    }
    for (let y = 0; y <= this.gridHeight; y++) {
      this.gridCacheCtx.moveTo(0, y * this.cellSize);
      this.gridCacheCtx.lineTo(this.gridCacheCanvas.width, y * this.cellSize);
    }
    this.gridCacheCtx.stroke();
    
    // 绘制主网格线（每5格一条粗线）到缓存
    this.gridCacheCtx.globalAlpha = 0.5;
    this.gridCacheCtx.strokeStyle = theme.primary;
    this.gridCacheCtx.lineWidth = 1.5;
    this.gridCacheCtx.shadowBlur = 2;
    
    this.gridCacheCtx.beginPath();
    for (let x = 0; x <= this.gridWidth; x += 5) {
      this.gridCacheCtx.moveTo(x * this.cellSize, 0);
      this.gridCacheCtx.lineTo(x * this.cellSize, this.gridCacheCanvas.height);
    }
    for (let y = 0; y <= this.gridHeight; y += 5) {
      this.gridCacheCtx.moveTo(0, y * this.cellSize);
      this.gridCacheCtx.lineTo(this.gridCacheCanvas.width, y * this.cellSize);
    }
    this.gridCacheCtx.stroke();
    
    this.gridCacheCtx.restore();
    
    // 将缓存画布保存到Map中
    const cacheCanvas = document.createElement('canvas');
    cacheCanvas.width = this.gridCacheCanvas.width;
    cacheCanvas.height = this.gridCacheCanvas.height;
    const cacheCtx = cacheCanvas.getContext('2d');
    cacheCtx.drawImage(this.gridCacheCanvas, 0, 0);
    
    this.gridCache.set(realmName, cacheCanvas);
  }
  
  drawGrid() {
    // 检查是否需要重新缓存网格
    const currentRealm = this.currentRealm.name;
    if (this.lastGridRealm !== currentRealm) {
      this.cacheGridForRealm(currentRealm);
      this.lastGridRealm = currentRealm;
    }
    
    // 绘制缓存的静态网格
    if (this.gridCache.has(currentRealm)) {
      this.ctx.drawImage(this.gridCache.get(currentRealm), 0, 0);
    }
    
    // 绘制动态效果层
    const time = Date.now() * 0.001;
    const realmIndex = this.realms.findIndex(realm => realm.name === this.currentRealm.name);
    
    const gridThemes = {
      0: { primary: '#40E0D0', secondary: '#20B2AA', glow: '#7FFFD4' },
      1: { primary: '#1E90FF', secondary: '#4169E1', glow: '#87CEEB' },
      2: { primary: '#FFD700', secondary: '#FFA500', glow: '#FFFF99' },
      3: { primary: '#9932CC', secondary: '#8A2BE2', glow: '#DDA0DD' },
      4: { primary: '#FF6347', secondary: '#DC143C', glow: '#FFA07A' },
      5: { primary: '#F5F5DC', secondary: '#DCDCDC', glow: '#FFFACD' }
    };
    
    const theme = gridThemes[realmIndex] || gridThemes[0];
    const glowIntensity = 0.5 + 0.3 * Math.sin(time * 1.5);
    
    this.ctx.save();
    
    // 绘制渐变边框效果
    if (realmIndex >= 2) { // 金丹期及以上显示特殊边框
      const gradient = this.ctx.createLinearGradient(0, 0, this.canvas.width, this.canvas.height);
      gradient.addColorStop(0, theme.primary + '60');
      gradient.addColorStop(0.5, theme.glow + '40');
      gradient.addColorStop(1, theme.primary + '60');
      
      this.ctx.globalAlpha = 0.7 * glowIntensity;
      this.ctx.strokeStyle = gradient;
      this.ctx.lineWidth = 3;
      this.ctx.shadowColor = theme.glow;
      this.ctx.shadowBlur = 10 * glowIntensity;
      this.ctx.strokeRect(2, 2, this.canvas.width - 4, this.canvas.height - 4);
    }
    
    // 绘制中心十字线（高级境界特效）
    if (realmIndex >= 4) { // 化神期及以上显示中心十字线
      const centerX = this.canvas.width / 2;
      const centerY = this.canvas.height / 2;
      
      this.ctx.globalAlpha = 0.8 * glowIntensity;
      this.ctx.strokeStyle = theme.glow;
      this.ctx.lineWidth = 2;
      this.ctx.shadowBlur = 10 * glowIntensity;
      
      this.ctx.beginPath();
      this.ctx.moveTo(centerX, 0);
      this.ctx.lineTo(centerX, this.canvas.height);
      this.ctx.moveTo(0, centerY);
      this.ctx.lineTo(this.canvas.width, centerY);
      this.ctx.stroke();
    }
    
    // 恢复状态
    this.ctx.restore();
  }
  
  drawFood() {
    const x = this.food.x * this.cellSize;
    const y = this.food.y * this.cellSize;
    const centerX = x + this.cellSize / 2;
    const centerY = y + this.cellSize / 2;
    const radius = this.cellSize / 3;
    const realmIndex = this.realms.findIndex(realm => realm.name === this.currentRealm.name);
    const effectIntensity = (realmIndex + 1) / this.realms.length;
    
    // 脉动光晕效果 - 强度递增
    const time = Date.now() * 0.003;
    const pulseIntensity = (Math.sin(time) + 1) * 0.5; // 0-1之间
    const glowRadius = radius * (1.8 + pulseIntensity * (0.5 + effectIntensity * 0.8));
    
    // 外层脉动光晕 - 根据境界调整颜色和强度
    const glowGradient = this.ctx.createRadialGradient(
      centerX, centerY, 0,
      centerX, centerY, glowRadius
    );
    
    if (realmIndex >= 3) { // 元婴期及以上 - 彩色光晕
      glowGradient.addColorStop(0, this.currentRealm.color + '80');
      glowGradient.addColorStop(0.3, '#FFD700' + '60');
      glowGradient.addColorStop(0.7, '#FF6347' + '40');
      glowGradient.addColorStop(1, '#FF634700');
    } else {
      glowGradient.addColorStop(0, '#FFD700' + Math.floor(80 + effectIntensity * 40).toString(16).padStart(2, '0'));
      glowGradient.addColorStop(0.5, '#FF6347' + Math.floor(40 + effectIntensity * 20).toString(16).padStart(2, '0'));
      glowGradient.addColorStop(1, '#FF634700');
    }
    
    this.ctx.fillStyle = glowGradient;
    this.ctx.beginPath();
    this.ctx.arc(centerX, centerY, glowRadius, 0, Math.PI * 2);
    this.ctx.fill();
    
    // 高级境界的特殊效果
    if (realmIndex >= 2) { // 金丹期及以上 - 旋转光环
      const rotationTime = Date.now() * 0.002;
      for (let i = 0; i < 3; i++) {
        const angle = rotationTime + (i * Math.PI * 2) / 3;
        const ringRadius = radius * (1.5 + Math.sin(time + i) * 0.2);
        const ringX = centerX + Math.cos(angle) * radius * 0.3;
        const ringY = centerY + Math.sin(angle) * radius * 0.3;
        
        this.ctx.strokeStyle = '#FFD700' + '60';
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        this.ctx.arc(ringX, ringY, ringRadius * 0.3, 0, Math.PI * 2);
        this.ctx.stroke();
      }
    }
    
    if (realmIndex >= 4) { // 化神期及以上 - 能量波动
      const waveTime = Date.now() * 0.004;
      for (let i = 0; i < 2; i++) {
        const waveRadius = radius * (2 + i * 0.5 + Math.sin(waveTime + i) * 0.3);
        this.ctx.strokeStyle = this.currentRealm.color + '40';
        this.ctx.lineWidth = 1;
        this.ctx.beginPath();
        this.ctx.arc(centerX, centerY, waveRadius, 0, Math.PI * 2);
        this.ctx.stroke();
      }
    }
    
    if (realmIndex >= 5) { // 飞升期 - 星光闪烁
      const sparkleTime = Date.now() * 0.006;
      const sparkleColors = ['#FFD700', '#FFFFFF', '#87CEEB', '#FF69B4'];
      
      for (let i = 0; i < 6; i++) {
        const angle = (sparkleTime + i * Math.PI / 3) % (Math.PI * 2);
        const distance = radius * (1.8 + Math.sin(sparkleTime + i) * 0.4);
        const sparkleX = centerX + Math.cos(angle) * distance;
        const sparkleY = centerY + Math.sin(angle) * distance;
        
        this.ctx.fillStyle = sparkleColors[i % sparkleColors.length] + '80';
        this.ctx.beginPath();
        this.ctx.arc(sparkleX, sparkleY, 2, 0, Math.PI * 2);
        this.ctx.fill();
      }
    }
    
    // 绘制食物图片
    const foodImage = this.foodImages[this.currentRealm.name];
    if (foodImage && foodImage.complete) {
      // 计算图片大小，根据境界调整
      const imageSize = this.cellSize * 0.8 * this.currentRealm.size;
      const imageX = centerX - imageSize / 2;
      const imageY = centerY - imageSize / 2;
      
      // 添加轻微的脉动效果
      const scale = 1 + pulseIntensity * 0.1;
      const scaledSize = imageSize * scale;
      const scaledX = centerX - scaledSize / 2;
      const scaledY = centerY - scaledSize / 2;
      const imageRadius = scaledSize / 2;
      
      // 保存当前状态
      this.ctx.save();
      
      // 绘制外层立体边框
      const borderGradient = this.ctx.createRadialGradient(
        centerX, centerY, imageRadius * 0.7,
        centerX, centerY, imageRadius * 1.1
      );
      borderGradient.addColorStop(0, 'rgba(255, 255, 255, 0.3)');
      borderGradient.addColorStop(0.5, this.currentRealm.color + '80');
      borderGradient.addColorStop(1, 'rgba(0, 0, 0, 0.5)');
      
      this.ctx.fillStyle = borderGradient;
      this.ctx.beginPath();
      this.ctx.arc(centerX, centerY, imageRadius * 1.05, 0, Math.PI * 2);
      this.ctx.fill();
      
      // 设置外阴影效果
      this.ctx.shadowColor = this.currentRealm.color;
      this.ctx.shadowBlur = 15 + effectIntensity * 15;
      this.ctx.shadowOffsetX = 3;
      this.ctx.shadowOffsetY = 3;
      
      // 绘制主体圆形背景（增强立体感）
      const bgGradient = this.ctx.createRadialGradient(
        centerX - imageRadius * 0.3, centerY - imageRadius * 0.3, 0,
        centerX, centerY, imageRadius
      );
      bgGradient.addColorStop(0, 'rgba(255, 255, 255, 0.4)');
      bgGradient.addColorStop(0.4, 'rgba(255, 255, 255, 0.1)');
      bgGradient.addColorStop(1, 'rgba(0, 0, 0, 0.3)');
      
      this.ctx.fillStyle = bgGradient;
      this.ctx.beginPath();
      this.ctx.arc(centerX, centerY, imageRadius, 0, Math.PI * 2);
      this.ctx.fill();
      
      // 重置阴影
      this.ctx.shadowColor = 'transparent';
      this.ctx.shadowBlur = 0;
      this.ctx.shadowOffsetX = 0;
      this.ctx.shadowOffsetY = 0;
      
      // 创建圆形裁剪路径
      this.ctx.beginPath();
      this.ctx.arc(centerX, centerY, imageRadius * 0.9, 0, Math.PI * 2);
      this.ctx.clip();
      
      // 绘制食物图片（会被裁剪成圆形）
      this.ctx.drawImage(foodImage, scaledX, scaledY, scaledSize, scaledSize);
      
      // 恢复状态以绘制高光效果
      this.ctx.restore();
      
      // 添加顶部高光效果
      const highlightGradient = this.ctx.createRadialGradient(
        centerX - imageRadius * 0.3, centerY - imageRadius * 0.3, 0,
        centerX - imageRadius * 0.3, centerY - imageRadius * 0.3, imageRadius * 0.6
      );
      highlightGradient.addColorStop(0, 'rgba(255, 255, 255, 0.6)');
      highlightGradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.2)');
      highlightGradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
      
      this.ctx.save();
      this.ctx.beginPath();
      this.ctx.arc(centerX, centerY, imageRadius * 0.9, 0, Math.PI * 2);
      this.ctx.clip();
      
      this.ctx.fillStyle = highlightGradient;
      this.ctx.beginPath();
      this.ctx.arc(centerX - imageRadius * 0.3, centerY - imageRadius * 0.3, imageRadius * 0.6, 0, Math.PI * 2);
      this.ctx.fill();
      
      this.ctx.restore();
      
      // 添加内阴影效果
      const innerShadowGradient = this.ctx.createRadialGradient(
        centerX, centerY, imageRadius * 0.6,
        centerX, centerY, imageRadius * 0.9
      );
      innerShadowGradient.addColorStop(0, 'rgba(0, 0, 0, 0)');
      innerShadowGradient.addColorStop(1, 'rgba(0, 0, 0, 0.3)');
      
      this.ctx.save();
      this.ctx.beginPath();
      this.ctx.arc(centerX, centerY, imageRadius * 0.9, 0, Math.PI * 2);
      this.ctx.clip();
      
      this.ctx.fillStyle = innerShadowGradient;
      this.ctx.beginPath();
      this.ctx.arc(centerX, centerY, imageRadius * 0.9, 0, Math.PI * 2);
      this.ctx.fill();
      
      this.ctx.restore();
    } else {
      // 如果图片未加载完成，绘制备用圆形
      const foodGradient = this.ctx.createRadialGradient(
        centerX, centerY, 0,
        centerX, centerY, radius
      );
      
      if (realmIndex >= 3) {
        foodGradient.addColorStop(0, '#FFFFFF');
        foodGradient.addColorStop(0.3, this.currentRealm.color);
        foodGradient.addColorStop(0.7, '#FFD700');
        foodGradient.addColorStop(1, '#8B0000');
      } else {
        foodGradient.addColorStop(0, '#FFD700');
        foodGradient.addColorStop(0.6, '#FF6347');
        foodGradient.addColorStop(1, '#8B0000');
      }
      
      this.ctx.fillStyle = foodGradient;
      this.ctx.beginPath();
      this.ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
      this.ctx.fill();
    }
  }
  
  drawSnake() {
    this.snake.forEach((segment, index) => {
      const x = segment.x * this.cellSize;
      const y = segment.y * this.cellSize;
      const isHead = index === 0;
      
      // 根据境界设置颜色和大小
      const size = this.cellSize * this.currentRealm.size;
      const offset = (size - this.cellSize) / 2;
      
      this.ctx.save();
      
      if (isHead) {
        // 绘制蛇头
        this.drawSnakeHead(x - offset, y - offset, size);
      } else {
        // 绘制蛇身
        this.drawSnakeBody(x - offset, y - offset, size, index);
      }
      
      this.ctx.restore();
    });
  }
  
  drawSnakeHead(x, y, size) {
    const centerX = x + size / 2;
    const centerY = y + size / 2;
    const radius = size / 2;
    const color = this.currentRealm.color;
    const realmIndex = this.realms.findIndex(realm => realm.name === this.currentRealm.name);
    
    // 根据境界调整效果强度
    const effectIntensity = (realmIndex + 1) / this.realms.length;
    const glowSize = 1.5 + effectIntensity * 1.5;
    const glowOpacity = Math.floor(30 + effectIntensity * 40);
    
    // 外层光晕
    const glowGradient = this.ctx.createRadialGradient(
      centerX, centerY, 0,
      centerX, centerY, radius * glowSize
    );
    glowGradient.addColorStop(0, color + glowOpacity.toString(16).padStart(2, '0'));
    glowGradient.addColorStop(0.7, color + Math.floor(glowOpacity * 0.5).toString(16).padStart(2, '0'));
    glowGradient.addColorStop(1, color + '00');
    
    this.ctx.fillStyle = glowGradient;
    this.ctx.beginPath();
    this.ctx.arc(centerX, centerY, radius * glowSize, 0, Math.PI * 2);
    this.ctx.fill();
    
    // 根据境界绘制不同形状的蛇头
    this.drawHeadShape(centerX, centerY, radius, realmIndex, color);
    
    // 高级境界的特殊效果
    if (realmIndex >= 2) { // 金丹期及以上
      // 流动光环
      const time = Date.now() * 0.003;
      const flowRadius = radius * (1.3 + Math.sin(time) * 0.2);
      const flowGradient = this.ctx.createRadialGradient(
        centerX, centerY, flowRadius * 0.8,
        centerX, centerY, flowRadius
      );
      flowGradient.addColorStop(0, color + '00');
      flowGradient.addColorStop(0.5, color + '60');
      flowGradient.addColorStop(1, color + '00');
      
      this.ctx.fillStyle = flowGradient;
      this.ctx.beginPath();
      this.ctx.arc(centerX, centerY, flowRadius, 0, Math.PI * 2);
      this.ctx.fill();
    }
    
    if (realmIndex >= 3) { // 元婴期及以上
      // 脉动能量环
      const pulseTime = Date.now() * 0.005;
      const pulseIntensity = (Math.sin(pulseTime) + 1) * 0.5;
      const pulseRadius = radius * (1.5 + pulseIntensity * 0.5);
      
      this.ctx.strokeStyle = color + Math.floor(60 + pulseIntensity * 40).toString(16).padStart(2, '0');
      this.ctx.lineWidth = 2 + pulseIntensity * 2;
      this.ctx.beginPath();
      this.ctx.arc(centerX, centerY, pulseRadius, 0, Math.PI * 2);
      this.ctx.stroke();
    }
    
    if (realmIndex >= 4) { // 化神期及以上
      // 电光效果
      const lightningTime = Date.now() * 0.01;
      if (Math.sin(lightningTime) > 0.7) {
        for (let i = 0; i < 3; i++) {
          const angle = (lightningTime + i * Math.PI * 0.67) % (Math.PI * 2);
          const startX = centerX + Math.cos(angle) * radius;
          const startY = centerY + Math.sin(angle) * radius;
          const endX = centerX + Math.cos(angle) * radius * 2;
          const endY = centerY + Math.sin(angle) * radius * 2;
          
          this.ctx.strokeStyle = '#FFFFFF80';
          this.ctx.lineWidth = 1;
          this.ctx.beginPath();
          this.ctx.moveTo(startX, startY);
          this.ctx.lineTo(endX, endY);
          this.ctx.stroke();
        }
      }
    }
    
    if (realmIndex >= 5) { // 渡劫期
      // 彩虹光环
      const rainbowTime = Date.now() * 0.002;
      const rainbowColors = ['#FF0000', '#FF7F00', '#FFFF00', '#00FF00', '#0000FF', '#4B0082', '#9400D3'];
      
      for (let i = 0; i < rainbowColors.length; i++) {
        const angle = (rainbowTime + i * Math.PI * 2 / rainbowColors.length) % (Math.PI * 2);
        const ringRadius = radius * (1.8 + Math.sin(rainbowTime + i) * 0.3);
        
        this.ctx.strokeStyle = rainbowColors[i] + '60';
        this.ctx.lineWidth = 1;
        this.ctx.beginPath();
        this.ctx.arc(centerX, centerY, ringRadius, angle, angle + Math.PI * 0.3);
        this.ctx.stroke();
      }
    }
    
    // 绘制蛇头主体渐变
    const headGradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
    headGradient.addColorStop(0, this.lightenColor(color, 0.3 + effectIntensity * 0.2));
    headGradient.addColorStop(0.6, color);
    headGradient.addColorStop(1, this.darkenColor(color, 0.2));
    
    this.ctx.fillStyle = headGradient;
    this.ctx.beginPath();
    this.ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
    this.ctx.fill();
    
    // 添加高光效果 - 强度递增
    const highlightIntensity = 0.4 + effectIntensity * 0.4;
    const highlightGradient = this.ctx.createRadialGradient(
      centerX - radius * 0.3, centerY - radius * 0.3, 0,
      centerX - radius * 0.3, centerY - radius * 0.3, radius * 0.6
    );
    highlightGradient.addColorStop(0, `rgba(255, 255, 255, ${highlightIntensity})`);
    highlightGradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
    
    this.ctx.fillStyle = highlightGradient;
    this.ctx.beginPath();
    this.ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
    this.ctx.fill();
    
    // 绘制眼睛 - 大小随境界增大
    const eyeRadius = radius * (0.25 + effectIntensity * 0.1);
    const eyeDistance = radius * 0.4;
    
    // 根据移动方向确定眼睛位置
    let eyeOffsetX = 0;
    let eyeOffsetY = 0;
    
    if (this.direction.x === 1) { // 向右
      eyeOffsetX = eyeDistance;
    } else if (this.direction.x === -1) { // 向左
      eyeOffsetX = -eyeDistance;
    } else if (this.direction.y === 1) { // 向下
      eyeOffsetY = eyeDistance;
    } else if (this.direction.y === -1) { // 向上
      eyeOffsetY = -eyeDistance;
    }
    
    // 绘制两只眼睛的白色部分
    this.ctx.fillStyle = 'white';
    
    // 第一只眼睛
    this.ctx.beginPath();
    if (this.direction.x !== 0) { // 水平移动
      this.ctx.arc(centerX + eyeOffsetX, centerY - eyeDistance/2, eyeRadius, 0, Math.PI * 2);
    } else { // 垂直移动
      this.ctx.arc(centerX - eyeDistance/2, centerY + eyeOffsetY, eyeRadius, 0, Math.PI * 2);
    }
    this.ctx.fill();
    
    // 第二只眼睛
    this.ctx.beginPath();
    if (this.direction.x !== 0) { // 水平移动
      this.ctx.arc(centerX + eyeOffsetX, centerY + eyeDistance/2, eyeRadius, 0, Math.PI * 2);
    } else { // 垂直移动
      this.ctx.arc(centerX + eyeDistance/2, centerY + eyeOffsetY, eyeRadius, 0, Math.PI * 2);
    }
    this.ctx.fill();
    
    // 绘制两只眼睛的黑色瞳孔
    this.ctx.fillStyle = 'black';
    const pupilRadius = eyeRadius * 0.6;
    
    // 第一只眼睛的瞳孔
    this.ctx.beginPath();
    if (this.direction.x !== 0) { // 水平移动
      this.ctx.arc(centerX + eyeOffsetX, centerY - eyeDistance/2, pupilRadius, 0, Math.PI * 2);
    } else { // 垂直移动
      this.ctx.arc(centerX - eyeDistance/2, centerY + eyeOffsetY, pupilRadius, 0, Math.PI * 2);
    }
    this.ctx.fill();
    
    // 第二只眼睛的瞳孔
    this.ctx.beginPath();
    if (this.direction.x !== 0) { // 水平移动
      this.ctx.arc(centerX + eyeOffsetX, centerY + eyeDistance/2, pupilRadius, 0, Math.PI * 2);
    } else { // 垂直移动
      this.ctx.arc(centerX + eyeDistance/2, centerY + eyeOffsetY, pupilRadius, 0, Math.PI * 2);
    }
    this.ctx.fill();
  }
  
  drawHeadShape(centerX, centerY, radius, realmIndex, color) {
    this.ctx.save();
    
    // 获取过渡期间的形状索引（蛇头使用第0段的索引）
    const transitionShapeIndex = this.getTransitionShapeIndex(0);
    const actualRealmIndex = transitionShapeIndex !== undefined ? transitionShapeIndex : realmIndex;
    
    // 如果在过渡期间，添加变形特效
    if (this.shapeTransition && this.shapeTransition.active) {
      this.drawShapeTransitionEffect(centerX, centerY, radius, 0);
    }
    
    switch(actualRealmIndex) {
      case 0: // 凡蛇期 - 圆形
        this.drawCircleHead(centerX, centerY, radius, color);
        break;
      case 1: // 筑基期 - 椭圆形
        this.drawEllipseHead(centerX, centerY, radius, color);
        break;
      case 2: // 金丹期 - 六边形
        this.drawHexagonHead(centerX, centerY, radius, color);
        break;
      case 3: // 元婴期 - 八角形
        this.drawOctagonHead(centerX, centerY, radius, color);
        break;
      case 4: // 化神期 - 龙头形状
        this.drawDragonHead(centerX, centerY, radius, color);
        break;
      case 5: // 飞升期 - 完整龙头
        this.drawFullDragonHead(centerX, centerY, radius, color);
        break;
      default:
        this.drawCircleHead(centerX, centerY, radius, color);
    }
    
    this.ctx.restore();
  }
  
  drawCircleHead(centerX, centerY, radius, color) {
    // 创建主体径向渐变
    const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
    const darkerColor = this.darkenColor(color, 0.3);
    const lighterColor = this.lightenColor(color, 0.2);
    
    gradient.addColorStop(0, lighterColor);
    gradient.addColorStop(0.7, color);
    gradient.addColorStop(1, darkerColor);
    
    this.ctx.fillStyle = gradient;
    this.ctx.beginPath();
    this.ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
    this.ctx.fill();
  }
  
  drawEllipseHead(centerX, centerY, radius, color) {
    // 椭圆形蛇头 - 更明显的拉伸效果
    const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
    const darkerColor = this.darkenColor(color, 0.4);
    const lighterColor = this.lightenColor(color, 0.3);
    
    gradient.addColorStop(0, lighterColor);
    gradient.addColorStop(0.6, color);
    gradient.addColorStop(1, darkerColor);
    
    this.ctx.fillStyle = gradient;
    this.ctx.beginPath();
    // 大幅增加椭圆的拉伸比例
    this.ctx.ellipse(centerX, centerY, radius * 1.6, radius * 0.6, 0, 0, Math.PI * 2);
    this.ctx.fill();
    
    // 添加椭圆边框强调形状
    this.ctx.strokeStyle = this.lightenColor(color, 0.4);
    this.ctx.lineWidth = 2;
    this.ctx.stroke();
  }
  
  drawHexagonHead(centerX, centerY, radius, color) {
    // 六边形蛇头 - 更大更明显
    const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius * 1.3);
    const darkerColor = this.darkenColor(color, 0.4);
    const lighterColor = this.lightenColor(color, 0.3);
    
    gradient.addColorStop(0, lighterColor);
    gradient.addColorStop(0.6, color);
    gradient.addColorStop(1, darkerColor);
    
    this.ctx.fillStyle = gradient;
    this.ctx.beginPath();
    
    // 增大六边形尺寸
    const hexRadius = radius * 1.3;
    for (let i = 0; i < 6; i++) {
      const angle = (i * Math.PI) / 3;
      const x = centerX + hexRadius * Math.cos(angle);
      const y = centerY + hexRadius * Math.sin(angle);
      
      if (i === 0) {
        this.ctx.moveTo(x, y);
      } else {
        this.ctx.lineTo(x, y);
      }
    }
    
    this.ctx.closePath();
    this.ctx.fill();
    
    // 添加六边形边框和内部装饰
    this.ctx.strokeStyle = this.lightenColor(color, 0.4);
    this.ctx.lineWidth = 3;
    this.ctx.stroke();
    
    // 添加内部六边形装饰
    this.ctx.fillStyle = this.lightenColor(color, 0.2);
    this.ctx.beginPath();
    const innerRadius = radius * 0.6;
    for (let i = 0; i < 6; i++) {
      const angle = (i * Math.PI) / 3;
      const x = centerX + innerRadius * Math.cos(angle);
      const y = centerY + innerRadius * Math.sin(angle);
      
      if (i === 0) {
        this.ctx.moveTo(x, y);
      } else {
        this.ctx.lineTo(x, y);
      }
    }
    this.ctx.closePath();
    this.ctx.fill();
  }
  
  drawOctagonHead(centerX, centerY, radius, color) {
    // 八角形蛇头 - 威严的元婴期形态
    const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius * 1.4);
    const darkerColor = this.darkenColor(color, 0.5);
    const lighterColor = this.lightenColor(color, 0.4);
    
    gradient.addColorStop(0, lighterColor);
    gradient.addColorStop(0.5, color);
    gradient.addColorStop(1, darkerColor);
    
    this.ctx.fillStyle = gradient;
    this.ctx.beginPath();
    
    // 增大八角形尺寸
    const octRadius = radius * 1.4;
    for (let i = 0; i < 8; i++) {
      const angle = (i * Math.PI) / 4;
      const x = centerX + octRadius * Math.cos(angle);
      const y = centerY + octRadius * Math.sin(angle);
      
      if (i === 0) {
        this.ctx.moveTo(x, y);
      } else {
        this.ctx.lineTo(x, y);
      }
    }
    
    this.ctx.closePath();
    this.ctx.fill();
    
    // 添加八角形边框
    this.ctx.strokeStyle = this.lightenColor(color, 0.5);
    this.ctx.lineWidth = 4;
    this.ctx.stroke();
    
    // 添加内部八角形装饰
    this.ctx.fillStyle = this.lightenColor(color, 0.3);
    this.ctx.beginPath();
    const innerRadius = radius * 0.7;
    for (let i = 0; i < 8; i++) {
      const angle = (i * Math.PI) / 4;
      const x = centerX + innerRadius * Math.cos(angle);
      const y = centerY + innerRadius * Math.sin(angle);
      
      if (i === 0) {
        this.ctx.moveTo(x, y);
      } else {
        this.ctx.lineTo(x, y);
      }
    }
    this.ctx.closePath();
    this.ctx.fill();
    
    // 添加中心光点
    const centerGradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius * 0.3);
    centerGradient.addColorStop(0, this.lightenColor(color, 0.6));
    centerGradient.addColorStop(1, 'transparent');
    this.ctx.fillStyle = centerGradient;
    this.ctx.beginPath();
    this.ctx.arc(centerX, centerY, radius * 0.3, 0, Math.PI * 2);
    this.ctx.fill();
  }
  
  drawDragonHead(centerX, centerY, radius, color) {
    // 龙头形状 - 威武的化神期龙头
    const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius * 1.5);
    const darkerColor = this.darkenColor(color, 0.4);
    const lighterColor = this.lightenColor(color, 0.4);
    
    gradient.addColorStop(0, lighterColor);
    gradient.addColorStop(0.5, color);
    gradient.addColorStop(1, darkerColor);
    
    this.ctx.fillStyle = gradient;
    
    // 绘制龙头主体 - 更大更威武
    this.ctx.beginPath();
    this.ctx.ellipse(centerX, centerY, radius * 1.6, radius * 1.1, 0, 0, Math.PI * 2);
    this.ctx.fill();
    
    // 添加龙头边框
    this.ctx.strokeStyle = this.lightenColor(color, 0.5);
    this.ctx.lineWidth = 3;
    this.ctx.stroke();
    
    // 绘制更大更威武的龙角
    this.ctx.fillStyle = this.lightenColor(color, 0.4);
    // 左角
    this.ctx.beginPath();
    this.ctx.moveTo(centerX - radius * 0.6, centerY - radius * 0.9);
    this.ctx.lineTo(centerX - radius * 0.4, centerY - radius * 1.5);
    this.ctx.lineTo(centerX - radius * 0.2, centerY - radius * 1.3);
    this.ctx.lineTo(centerX - radius * 0.3, centerY - radius * 0.8);
    this.ctx.closePath();
    this.ctx.fill();
    
    // 右角
    this.ctx.beginPath();
    this.ctx.moveTo(centerX + radius * 0.6, centerY - radius * 0.9);
    this.ctx.lineTo(centerX + radius * 0.4, centerY - radius * 1.5);
    this.ctx.lineTo(centerX + radius * 0.2, centerY - radius * 1.3);
    this.ctx.lineTo(centerX + radius * 0.3, centerY - radius * 0.8);
    this.ctx.closePath();
    this.ctx.fill();
    
    // 添加龙角边框
    this.ctx.strokeStyle = this.lightenColor(color, 0.6);
    this.ctx.lineWidth = 2;
    this.ctx.stroke();
    
    // 绘制龙眼
    this.ctx.fillStyle = this.lightenColor(color, 0.7);
    this.ctx.beginPath();
    this.ctx.arc(centerX - radius * 0.4, centerY - radius * 0.2, radius * 0.15, 0, Math.PI * 2);
    this.ctx.fill();
    this.ctx.beginPath();
    this.ctx.arc(centerX + radius * 0.4, centerY - radius * 0.2, radius * 0.15, 0, Math.PI * 2);
    this.ctx.fill();
    
    // 绘制龙鼻孔
    this.ctx.fillStyle = this.darkenColor(color, 0.6);
    this.ctx.beginPath();
    this.ctx.ellipse(centerX - radius * 0.15, centerY + radius * 0.3, radius * 0.08, radius * 0.12, 0, 0, Math.PI * 2);
    this.ctx.fill();
    this.ctx.beginPath();
    this.ctx.ellipse(centerX + radius * 0.15, centerY + radius * 0.3, radius * 0.08, radius * 0.12, 0, 0, Math.PI * 2);
    this.ctx.fill();
  }
  
  drawFullDragonHead(centerX, centerY, radius, color) {
    // 完整龙头 - 最华丽的形状
    const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
    const darkerColor = this.darkenColor(color, 0.3);
    const lighterColor = this.lightenColor(color, 0.2);
    
    gradient.addColorStop(0, lighterColor);
    gradient.addColorStop(0.5, color);
    gradient.addColorStop(1, darkerColor);
    
    this.ctx.fillStyle = gradient;
    
    // 绘制龙头主体 - 更大更威武
    this.ctx.beginPath();
    this.ctx.ellipse(centerX, centerY, radius * 1.4, radius, 0, 0, Math.PI * 2);
    this.ctx.fill();
    
    // 绘制龙鼻
    this.ctx.fillStyle = this.lightenColor(color, 0.4);
    this.ctx.beginPath();
    this.ctx.ellipse(centerX + radius * 0.8, centerY, radius * 0.3, radius * 0.2, 0, 0, Math.PI * 2);
    this.ctx.fill();
    
    // 绘制龙角 - 更大更华丽
    this.ctx.fillStyle = '#FFD700'; // 金色龙角
    this.ctx.beginPath();
    this.ctx.moveTo(centerX - radius * 0.6, centerY - radius * 0.8);
    this.ctx.lineTo(centerX - radius * 0.4, centerY - radius * 1.4);
    this.ctx.lineTo(centerX - radius * 0.2, centerY - radius * 1.1);
    this.ctx.lineTo(centerX - radius * 0.1, centerY - radius * 0.9);
    this.ctx.closePath();
    this.ctx.fill();
    
    this.ctx.beginPath();
    this.ctx.moveTo(centerX + radius * 0.6, centerY - radius * 0.8);
    this.ctx.lineTo(centerX + radius * 0.4, centerY - radius * 1.4);
    this.ctx.lineTo(centerX + radius * 0.2, centerY - radius * 1.1);
    this.ctx.lineTo(centerX + radius * 0.1, centerY - radius * 0.9);
    this.ctx.closePath();
    this.ctx.fill();
    
    // 绘制龙须
    this.ctx.strokeStyle = this.lightenColor(color, 0.3);
    this.ctx.lineWidth = 2;
    this.ctx.beginPath();
    this.ctx.moveTo(centerX + radius * 1.2, centerY - radius * 0.3);
    this.ctx.quadraticCurveTo(centerX + radius * 1.8, centerY - radius * 0.1, centerX + radius * 1.6, centerY + radius * 0.2);
    this.ctx.stroke();
    
    this.ctx.beginPath();
    this.ctx.moveTo(centerX + radius * 1.2, centerY + radius * 0.3);
    this.ctx.quadraticCurveTo(centerX + radius * 1.8, centerY + radius * 0.1, centerX + radius * 1.6, centerY - radius * 0.2);
    this.ctx.stroke();
  }
   
   drawBodyGlow(centerX, centerY, glowRadius, baseColor, effectIntensity, flowIntensity) {
     // 外层光晕效果
     const flowGlow = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, glowRadius);
     const glowOpacity = Math.floor(20 + effectIntensity * 30 + flowIntensity * 20);
     const glowAlpha = glowOpacity.toString(16).padStart(2, '0');
     flowGlow.addColorStop(0, baseColor + glowAlpha);
     flowGlow.addColorStop(0.7, baseColor + '20');
     flowGlow.addColorStop(1, baseColor + '00');
     
     this.ctx.fillStyle = flowGlow;
     this.ctx.beginPath();
     this.ctx.arc(centerX, centerY, glowRadius, 0, Math.PI * 2);
     this.ctx.fill();
   }
   
   drawBodyShape(centerX, centerY, radius, realmIndex, baseColor, segmentIndex, flowIntensity) {
     this.ctx.save();
     
     // 获取过渡期间的形状索引
     const transitionShapeIndex = this.getTransitionShapeIndex(segmentIndex);
     const actualRealmIndex = transitionShapeIndex !== undefined ? transitionShapeIndex : realmIndex;
     
     // 如果在过渡期间，添加变形特效
     if (this.shapeTransition && this.shapeTransition.active) {
       this.drawShapeTransitionEffect(centerX, centerY, radius, segmentIndex);
     }
     
     switch(actualRealmIndex) {
       case 0: // 凡蛇期 - 圆形
         this.drawCircleBody(centerX, centerY, radius, baseColor, flowIntensity);
         break;
       case 1: // 筑基期 - 椭圆形
         this.drawEllipseBody(centerX, centerY, radius, baseColor, flowIntensity);
         break;
       case 2: // 金丹期 - 六边形
         this.drawHexagonBody(centerX, centerY, radius, baseColor, flowIntensity);
         break;
       case 3: // 元婴期 - 八角形
         this.drawOctagonBody(centerX, centerY, radius, baseColor, flowIntensity);
         break;
       case 4: // 化神期 - 龙鳞形
         this.drawDragonScaleBody(centerX, centerY, radius, baseColor, flowIntensity, segmentIndex);
         break;
       case 5: // 飞升期 - 龙身形
         this.drawDragonBody(centerX, centerY, radius, baseColor, flowIntensity, segmentIndex);
         break;
       default:
         this.drawCircleBody(centerX, centerY, radius, baseColor, flowIntensity);
     }
     
     this.ctx.restore();
   }
   
   drawCircleBody(centerX, centerY, radius, baseColor, flowIntensity) {
     // 创建主体径向渐变
     const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
     const darkerColor = this.darkenColor(baseColor, 0.2);
     const lighterColor = this.lightenColor(baseColor, 0.1 + flowIntensity * 0.2);
     
     gradient.addColorStop(0, lighterColor);
     gradient.addColorStop(0.7, baseColor);
     gradient.addColorStop(1, darkerColor);
     
     this.ctx.fillStyle = gradient;
     this.ctx.beginPath();
     this.ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
     this.ctx.fill();
     
     // 动态高光点
     if (flowIntensity > 0.8) {
       const highlightIntensity = (flowIntensity - 0.8) * 5;
       const sparkleGradient = this.ctx.createRadialGradient(
         centerX - radius * 0.2, centerY - radius * 0.2, 0,
         centerX - radius * 0.2, centerY - radius * 0.2, radius * 0.4
       );
       sparkleGradient.addColorStop(0, `rgba(255, 255, 255, ${Math.min(highlightIntensity, 0.8)})`);
       sparkleGradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
       
       this.ctx.fillStyle = sparkleGradient;
       this.ctx.beginPath();
       this.ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
       this.ctx.fill();
     }
   }
   
   drawEllipseBody(centerX, centerY, radius, baseColor, flowIntensity) {
     // 椭圆形蛇身 - 增强拉伸效果
     const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius * 1.4);
     const darkerColor = this.darkenColor(baseColor, 0.3);
     const lighterColor = this.lightenColor(baseColor, 0.2 + flowIntensity * 0.3);
     
     gradient.addColorStop(0, lighterColor);
     gradient.addColorStop(0.6, baseColor);
     gradient.addColorStop(1, darkerColor);
     
     this.ctx.fillStyle = gradient;
     this.ctx.beginPath();
     this.ctx.ellipse(centerX, centerY, radius * 1.5, radius * 0.7, 0, 0, Math.PI * 2);
     this.ctx.fill();
     
     // 添加边框强调形状
     this.ctx.strokeStyle = this.darkenColor(baseColor, 0.4);
     this.ctx.lineWidth = 2;
     this.ctx.beginPath();
     this.ctx.ellipse(centerX, centerY, radius * 1.5, radius * 0.7, 0, 0, Math.PI * 2);
     this.ctx.stroke();
   }
   
   drawHexagonBody(centerX, centerY, radius, baseColor, flowIntensity) {
     // 六边形蛇身 - 增强棱角效果
     const hexRadius = radius * 1.1;
     const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, hexRadius);
     const darkerColor = this.darkenColor(baseColor, 0.3);
     const lighterColor = this.lightenColor(baseColor, 0.2 + flowIntensity * 0.3);
     
     gradient.addColorStop(0, lighterColor);
     gradient.addColorStop(0.6, baseColor);
     gradient.addColorStop(1, darkerColor);
     
     this.ctx.fillStyle = gradient;
     this.ctx.beginPath();
     
     for (let i = 0; i < 6; i++) {
       const angle = (i * Math.PI) / 3;
       const x = centerX + hexRadius * Math.cos(angle);
       const y = centerY + hexRadius * Math.sin(angle);
       
       if (i === 0) {
         this.ctx.moveTo(x, y);
       } else {
         this.ctx.lineTo(x, y);
       }
     }
     
     this.ctx.closePath();
     this.ctx.fill();
     
     // 添加边框强调六边形
     this.ctx.strokeStyle = this.darkenColor(baseColor, 0.4);
     this.ctx.lineWidth = 2;
     this.ctx.beginPath();
     for (let i = 0; i < 6; i++) {
       const angle = (i * Math.PI) / 3;
       const x = centerX + hexRadius * Math.cos(angle);
       const y = centerY + hexRadius * Math.sin(angle);
       
       if (i === 0) {
         this.ctx.moveTo(x, y);
       } else {
         this.ctx.lineTo(x, y);
       }
     }
     this.ctx.closePath();
     this.ctx.stroke();
     
     // 内部装饰线条
     this.ctx.strokeStyle = this.lightenColor(baseColor, 0.3);
     this.ctx.lineWidth = 1;
     for (let i = 0; i < 6; i++) {
       const angle = (i * Math.PI) / 3;
       this.ctx.beginPath();
       this.ctx.moveTo(centerX, centerY);
       this.ctx.lineTo(centerX + hexRadius * 0.7 * Math.cos(angle), centerY + hexRadius * 0.7 * Math.sin(angle));
       this.ctx.stroke();
     }
   }
   
   drawOctagonBody(centerX, centerY, radius, baseColor, flowIntensity) {
     // 八角形蛇身 - 增强威严效果
     const octRadius = radius * 1.15;
     const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, octRadius);
     const darkerColor = this.darkenColor(baseColor, 0.3);
     const lighterColor = this.lightenColor(baseColor, 0.2 + flowIntensity * 0.3);
     
     gradient.addColorStop(0, lighterColor);
     gradient.addColorStop(0.5, baseColor);
     gradient.addColorStop(1, darkerColor);
     
     this.ctx.fillStyle = gradient;
     this.ctx.beginPath();
     
     for (let i = 0; i < 8; i++) {
       const angle = (i * Math.PI) / 4;
       const x = centerX + octRadius * Math.cos(angle);
       const y = centerY + octRadius * Math.sin(angle);
       
       if (i === 0) {
         this.ctx.moveTo(x, y);
       } else {
         this.ctx.lineTo(x, y);
       }
     }
     
     this.ctx.closePath();
     this.ctx.fill();
     
     // 添加边框强调八角形
     this.ctx.strokeStyle = this.darkenColor(baseColor, 0.4);
     this.ctx.lineWidth = 2;
     this.ctx.beginPath();
     for (let i = 0; i < 8; i++) {
       const angle = (i * Math.PI) / 4;
       const x = centerX + octRadius * Math.cos(angle);
       const y = centerY + octRadius * Math.sin(angle);
       
       if (i === 0) {
         this.ctx.moveTo(x, y);
       } else {
         this.ctx.lineTo(x, y);
       }
     }
     this.ctx.closePath();
     this.ctx.stroke();
     
     // 内部装饰 - 十字线
     this.ctx.strokeStyle = this.lightenColor(baseColor, 0.3);
     this.ctx.lineWidth = 1.5;
     this.ctx.beginPath();
     this.ctx.moveTo(centerX - octRadius * 0.6, centerY);
     this.ctx.lineTo(centerX + octRadius * 0.6, centerY);
     this.ctx.moveTo(centerX, centerY - octRadius * 0.6);
     this.ctx.lineTo(centerX, centerY + octRadius * 0.6);
     this.ctx.stroke();
     
     // 中心光点
     const centerGlow = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, octRadius * 0.3);
     centerGlow.addColorStop(0, this.lightenColor(baseColor, 0.5));
     centerGlow.addColorStop(1, 'transparent');
     this.ctx.fillStyle = centerGlow;
     this.ctx.beginPath();
     this.ctx.arc(centerX, centerY, octRadius * 0.3, 0, Math.PI * 2);
     this.ctx.fill();
   }
   
   drawDragonScaleBody(centerX, centerY, radius, baseColor, flowIntensity, segmentIndex) {
     // 龙鳞形蛇身 - 增强鳞片效果
     const scaleRadius = radius * 1.1;
     const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, scaleRadius);
     const darkerColor = this.darkenColor(baseColor, 0.3);
     const lighterColor = this.lightenColor(baseColor, 0.2 + flowIntensity * 0.3);
     
     gradient.addColorStop(0, lighterColor);
     gradient.addColorStop(0.5, baseColor);
     gradient.addColorStop(1, darkerColor);
     
     this.ctx.fillStyle = gradient;
     
     // 绘制主体圆形
     this.ctx.beginPath();
     this.ctx.arc(centerX, centerY, scaleRadius, 0, Math.PI * 2);
     this.ctx.fill();
     
     // 添加边框
     this.ctx.strokeStyle = this.darkenColor(baseColor, 0.4);
     this.ctx.lineWidth = 2;
     this.ctx.beginPath();
     this.ctx.arc(centerX, centerY, scaleRadius, 0, Math.PI * 2);
     this.ctx.stroke();
     
     // 绘制龙鳞纹理 - 更密集的鳞片
     this.ctx.strokeStyle = '#FFD700'; // 金色鳞片
     this.ctx.lineWidth = 1.5;
     
     // 绘制主要鳞片线条
     const scaleOffset = segmentIndex * 0.2;
     for (let i = 0; i < 6; i++) {
       const angle = (i * Math.PI) / 3 + scaleOffset;
       const startX = centerX + scaleRadius * 0.2 * Math.cos(angle);
       const startY = centerY + scaleRadius * 0.2 * Math.sin(angle);
       const endX = centerX + scaleRadius * 0.9 * Math.cos(angle);
       const endY = centerY + scaleRadius * 0.9 * Math.sin(angle);
       
       this.ctx.beginPath();
       this.ctx.moveTo(startX, startY);
       this.ctx.lineTo(endX, endY);
       this.ctx.stroke();
     }
     
     // 绘制次要鳞片线条
     this.ctx.strokeStyle = this.lightenColor(baseColor, 0.4);
     this.ctx.lineWidth = 1;
     for (let i = 0; i < 6; i++) {
       const angle = (i * Math.PI) / 3 + scaleOffset + Math.PI / 6;
       const startX = centerX + scaleRadius * 0.4 * Math.cos(angle);
       const startY = centerY + scaleRadius * 0.4 * Math.sin(angle);
       const endX = centerX + scaleRadius * 0.7 * Math.cos(angle);
       const endY = centerY + scaleRadius * 0.7 * Math.sin(angle);
       
       this.ctx.beginPath();
       this.ctx.moveTo(startX, startY);
       this.ctx.lineTo(endX, endY);
       this.ctx.stroke();
     }
     
     // 中心鳞片光芒
     const scaleGlow = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, scaleRadius * 0.4);
     scaleGlow.addColorStop(0, 'rgba(255, 215, 0, 0.6)');
     scaleGlow.addColorStop(1, 'transparent');
     this.ctx.fillStyle = scaleGlow;
     this.ctx.beginPath();
     this.ctx.arc(centerX, centerY, scaleRadius * 0.4, 0, Math.PI * 2);
     this.ctx.fill();
   }
   
   drawDragonBody(centerX, centerY, radius, baseColor, flowIntensity, segmentIndex) {
     // 龙身形蛇身 - 最华丽的形状
     const dragonRadius = radius * 1.2;
     const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, dragonRadius);
     const darkerColor = this.darkenColor(baseColor, 0.3);
     const lighterColor = this.lightenColor(baseColor, 0.3 + flowIntensity * 0.4);
     
     gradient.addColorStop(0, lighterColor);
     gradient.addColorStop(0.4, baseColor);
     gradient.addColorStop(1, darkerColor);
     
     this.ctx.fillStyle = gradient;
     
     // 绘制龙身主体 - 更复杂的椭圆形状
     this.ctx.beginPath();
     this.ctx.ellipse(centerX, centerY, dragonRadius * 1.3, dragonRadius * 0.8, 0, 0, Math.PI * 2);
     this.ctx.fill();
     
     // 添加华丽边框
     this.ctx.strokeStyle = '#FFD700'; // 金色边框
     this.ctx.lineWidth = 3;
     this.ctx.beginPath();
     this.ctx.ellipse(centerX, centerY, dragonRadius * 1.3, dragonRadius * 0.8, 0, 0, Math.PI * 2);
     this.ctx.stroke();
     
     // 绘制龙鳞纹理 - 更密集华丽
     this.ctx.strokeStyle = '#FFD700'; // 金色鳞片
     this.ctx.lineWidth = 2;
     
     const scaleOffset = segmentIndex * 0.15;
     for (let i = 0; i < 8; i++) {
       const angle = (i * Math.PI) / 4 + scaleOffset;
       const startX = centerX + dragonRadius * 0.2 * Math.cos(angle);
       const startY = centerY + dragonRadius * 0.2 * Math.sin(angle);
       const endX = centerX + dragonRadius * 1.1 * Math.cos(angle);
       const endY = centerY + dragonRadius * 1.1 * Math.sin(angle);
       
       this.ctx.beginPath();
       this.ctx.moveTo(startX, startY);
       this.ctx.lineTo(endX, endY);
       this.ctx.stroke();
     }
     
     // 绘制次要龙鳞纹理
     this.ctx.strokeStyle = this.lightenColor(baseColor, 0.5);
     this.ctx.lineWidth = 1;
     for (let i = 0; i < 8; i++) {
       const angle = (i * Math.PI) / 4 + scaleOffset + Math.PI / 8;
       const startX = centerX + dragonRadius * 0.4 * Math.cos(angle);
       const startY = centerY + dragonRadius * 0.4 * Math.sin(angle);
       const endX = centerX + dragonRadius * 0.8 * Math.cos(angle);
       const endY = centerY + dragonRadius * 0.8 * Math.sin(angle);
       
       this.ctx.beginPath();
       this.ctx.moveTo(startX, startY);
       this.ctx.lineTo(endX, endY);
       this.ctx.stroke();
     }
     
     // 绘制华丽龙脊
     this.ctx.strokeStyle = '#FFD700';
     this.ctx.lineWidth = 3;
     this.ctx.beginPath();
     this.ctx.moveTo(centerX - dragonRadius * 1.0, centerY);
     this.ctx.lineTo(centerX + dragonRadius * 1.0, centerY);
     this.ctx.stroke();
     
     // 绘制龙脊装饰
     this.ctx.strokeStyle = this.lightenColor(baseColor, 0.6);
     this.ctx.lineWidth = 1;
     this.ctx.beginPath();
     this.ctx.moveTo(centerX, centerY - dragonRadius * 0.6);
     this.ctx.lineTo(centerX, centerY + dragonRadius * 0.6);
     this.ctx.stroke();
     
     // 中心龙珠光芒
     const dragonGlow = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, dragonRadius * 0.5);
     dragonGlow.addColorStop(0, 'rgba(255, 215, 0, 0.8)');
     dragonGlow.addColorStop(0.5, 'rgba(255, 255, 255, 0.4)');
     dragonGlow.addColorStop(1, 'transparent');
     this.ctx.fillStyle = dragonGlow;
     this.ctx.beginPath();
     this.ctx.arc(centerX, centerY, dragonRadius * 0.5, 0, Math.PI * 2);
     this.ctx.fill();
     
     // 龙珠核心
     const dragonCore = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, dragonRadius * 0.2);
     dragonCore.addColorStop(0, '#FFFFFF');
     dragonCore.addColorStop(1, '#FFD700');
     this.ctx.fillStyle = dragonCore;
     this.ctx.beginPath();
     this.ctx.arc(centerX, centerY, dragonRadius * 0.2, 0, Math.PI * 2);
     this.ctx.fill();
   }
   
   // 颜色辅助方法
   darkenColor(color, factor) {
     // 将十六进制颜色变暗
     const hex = color.replace('#', '');
     const r = parseInt(hex.substr(0, 2), 16);
     const g = parseInt(hex.substr(2, 2), 16);
     const b = parseInt(hex.substr(4, 2), 16);
     
     const newR = Math.floor(r * (1 - factor));
     const newG = Math.floor(g * (1 - factor));
     const newB = Math.floor(b * (1 - factor));
     
     return `#${newR.toString(16).padStart(2, '0')}${newG.toString(16).padStart(2, '0')}${newB.toString(16).padStart(2, '0')}`;
   }
   
   drawShapeTransitionEffect(centerX, centerY, radius, segmentIndex) {
     if (!this.shapeTransition || !this.shapeTransition.active) return;
     
     const progress = this.shapeTransition.progress;
     const time = Date.now() * 0.01;
     
     // 绘制变形能量环
     this.ctx.save();
     this.ctx.globalAlpha = 0.6 * (1 - progress); // 随着过渡进行逐渐消失
     
     // 创建变形光环
     const ringCount = 3;
     for (let i = 0; i < ringCount; i++) {
       const ringRadius = radius * (1.2 + i * 0.3 + Math.sin(time + segmentIndex + i) * 0.1);
       const ringGradient = this.ctx.createRadialGradient(
         centerX, centerY, ringRadius * 0.8,
         centerX, centerY, ringRadius
       );
       
       ringGradient.addColorStop(0, this.currentRealm.color + '00');
       ringGradient.addColorStop(0.5, this.currentRealm.color + '80');
       ringGradient.addColorStop(1, this.currentRealm.color + '00');
       
       this.ctx.strokeStyle = ringGradient;
       this.ctx.lineWidth = 2;
       this.ctx.beginPath();
       this.ctx.arc(centerX, centerY, ringRadius, 0, Math.PI * 2);
       this.ctx.stroke();
     }
     
     // 绘制变形粒子
     const particleCount = 6;
     for (let i = 0; i < particleCount; i++) {
       const angle = (time + segmentIndex + i * Math.PI / 3) % (Math.PI * 2);
       const particleRadius = radius * (1.5 + Math.sin(time * 2 + i) * 0.3);
       const particleX = centerX + Math.cos(angle) * particleRadius;
       const particleY = centerY + Math.sin(angle) * particleRadius;
       
       const particleGradient = this.ctx.createRadialGradient(
         particleX, particleY, 0,
         particleX, particleY, 4
       );
       
       particleGradient.addColorStop(0, this.currentRealm.color + 'FF');
       particleGradient.addColorStop(1, this.currentRealm.color + '00');
       
       this.ctx.fillStyle = particleGradient;
       this.ctx.beginPath();
       this.ctx.arc(particleX, particleY, 3, 0, Math.PI * 2);
       this.ctx.fill();
     }
     
     this.ctx.restore();
   }
   
   lightenColor(color, factor) {
     // 将十六进制颜色变亮
     const hex = color.replace('#', '');
     const r = parseInt(hex.substr(0, 2), 16);
     const g = parseInt(hex.substr(2, 2), 16);
     const b = parseInt(hex.substr(4, 2), 16);
     
     const newR = Math.min(255, Math.floor(r + (255 - r) * factor));
     const newG = Math.min(255, Math.floor(g + (255 - g) * factor));
     const newB = Math.min(255, Math.floor(b + (255 - b) * factor));
     
     return `#${newR.toString(16).padStart(2, '0')}${newG.toString(16).padStart(2, '0')}${newB.toString(16).padStart(2, '0')}`;
   }
   
   drawSnakeBody(x, y, size, segmentIndex) {
    const centerX = x + size / 2;
    const centerY = y + size / 2;
    const radius = size / 2;
    const baseColor = this.currentRealm.color;
    const realmIndex = this.realms.findIndex(realm => realm.name === this.currentRealm.name);
    const effectIntensity = (realmIndex + 1) / this.realms.length;
    
    // 基础流光动画效果
    const time = Date.now() * 0.003;
    const flowOffset = (time + segmentIndex * 0.5) % (Math.PI * 2);
    const flowIntensity = (Math.sin(flowOffset) + 1) * 0.5;
    
    // 根据境界调整光晕强度
    const glowMultiplier = 0.8 + effectIntensity * 0.7;
    const glowRadius = radius * (1.1 + flowIntensity * 0.2 * glowMultiplier);
    
    // 绘制基础光晕效果
     this.drawBodyGlow(centerX, centerY, glowRadius, baseColor, effectIntensity, flowIntensity);
     
     // 根据境界绘制不同形状的蛇身
     this.drawBodyShape(centerX, centerY, radius, realmIndex, baseColor, segmentIndex, flowIntensity);
    
    // 筑基期及以上：增强脉动效果
    if (realmIndex >= 1) {
      const pulseTime = Date.now() * 0.003;
      const pulseIntensity = (Math.sin(pulseTime + segmentIndex * 0.3) + 1) * 0.5;
      const pulseRadius = radius * (1.2 + pulseIntensity * 0.3);
      
      this.ctx.strokeStyle = baseColor + Math.floor(30 + pulseIntensity * 30).toString(16).padStart(2, '0');
      this.ctx.lineWidth = 1 + pulseIntensity;
      this.ctx.beginPath();
      this.ctx.arc(centerX, centerY, pulseRadius, 0, Math.PI * 2);
      this.ctx.stroke();
    }
    
    // 金丹期及以上：流动光环
    if (realmIndex >= 2) {
      const flowTime = Date.now() * 0.004;
      const flowOffset = segmentIndex * 0.4;
      const flowRadius = radius * (1.4 + Math.sin(flowTime + flowOffset) * 0.2);
      
      const flowGradient = this.ctx.createRadialGradient(
        centerX, centerY, flowRadius * 0.7,
        centerX, centerY, flowRadius
      );
      flowGradient.addColorStop(0, baseColor + '00');
      flowGradient.addColorStop(0.5, baseColor + '50');
      flowGradient.addColorStop(1, baseColor + '00');
      
      this.ctx.fillStyle = flowGradient;
      this.ctx.beginPath();
      this.ctx.arc(centerX, centerY, flowRadius, 0, Math.PI * 2);
      this.ctx.fill();
    }
    
    // 元婴期及以上：能量波动
    if (realmIndex >= 3) {
      const waveTime = Date.now() * 0.006;
      const waveIntensity = (Math.sin(waveTime + segmentIndex * 0.2) + 1) * 0.5;
      
      for (let i = 0; i < 2; i++) {
        const waveRadius = radius * (1.3 + i * 0.2 + waveIntensity * 0.3);
        this.ctx.strokeStyle = baseColor + Math.floor(20 + waveIntensity * 40).toString(16).padStart(2, '0');
        this.ctx.lineWidth = 1;
        this.ctx.beginPath();
        this.ctx.arc(centerX, centerY, waveRadius, 0, Math.PI * 2);
        this.ctx.stroke();
      }
    }
    
    // 化神期及以上：电光粒子
    if (realmIndex >= 4) {
      const sparkTime = Date.now() * 0.008;
      if (Math.sin(sparkTime + segmentIndex) > 0.6) {
        for (let i = 0; i < 2; i++) {
          const angle = (sparkTime + segmentIndex + i * Math.PI) % (Math.PI * 2);
          const sparkX = centerX + Math.cos(angle) * radius * 0.8;
          const sparkY = centerY + Math.sin(angle) * radius * 0.8;
          
          this.ctx.fillStyle = '#FFFFFF80';
          this.ctx.beginPath();
          this.ctx.arc(sparkX, sparkY, 1, 0, Math.PI * 2);
          this.ctx.fill();
        }
      }
    }
    
    // 渡劫期：星光粒子
    if (realmIndex >= 5) {
      const starTime = Date.now() * 0.002;
      const starColors = ['#FFD700', '#FFFFFF', '#87CEEB', '#FF69B4'];
      
      for (let i = 0; i < 4; i++) {
        const angle = (starTime + segmentIndex * 0.5 + i * Math.PI * 0.5) % (Math.PI * 2);
        const distance = radius * (0.6 + Math.sin(starTime + i) * 0.3);
        const starX = centerX + Math.cos(angle) * distance;
        const starY = centerY + Math.sin(angle) * distance;
        
        this.ctx.fillStyle = starColors[i] + '60';
        this.ctx.beginPath();
        this.ctx.arc(starX, starY, 1.5, 0, Math.PI * 2);
        this.ctx.fill();
      }
    }
    
    // 创建主体径向渐变（亮度随境界和流光变化）
    const gradient = this.ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
    const darkerColor = this.darkenColor(baseColor, 0.2 + effectIntensity * 0.1);
    const lighterColor = this.lightenColor(baseColor, 0.1 + effectIntensity * 0.2 + flowIntensity * 0.2);
    
    gradient.addColorStop(0, lighterColor);  // 中心亮色（随流光变化）
    gradient.addColorStop(0.7, baseColor);   // 中间原色
    gradient.addColorStop(1, darkerColor);   // 边缘暗色
    
    // 绘制蛇身圆形，使用渐变色
    this.ctx.fillStyle = gradient;
    this.ctx.beginPath();
    this.ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
    this.ctx.fill();
    
    // 动态高光点（强度随境界递增）
    const highlightThreshold = 0.9 - effectIntensity * 0.2; // 高级境界更容易触发高光
    if (flowIntensity > highlightThreshold) {
      const highlightIntensity = (flowIntensity - highlightThreshold) * (1 + effectIntensity);
      const sparkleGradient = this.ctx.createRadialGradient(
        centerX - radius * 0.2, centerY - radius * 0.2, 0,
        centerX - radius * 0.2, centerY - radius * 0.2, radius * 0.4
      );
      sparkleGradient.addColorStop(0, `rgba(255, 255, 255, ${Math.min(highlightIntensity, 0.8)})`);
      sparkleGradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
      
      this.ctx.fillStyle = sparkleGradient;
      this.ctx.beginPath();
      this.ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
      this.ctx.fill();
    }
  }
  
  // 颜色辅助函数
  darkenColor(color, factor) {
    const hex = color.replace('#', '');
    const r = Math.max(0, Math.floor(parseInt(hex.substr(0, 2), 16) * (1 - factor)));
    const g = Math.max(0, Math.floor(parseInt(hex.substr(2, 2), 16) * (1 - factor)));
    const b = Math.max(0, Math.floor(parseInt(hex.substr(4, 2), 16) * (1 - factor)));
    return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
  }
  
  lightenColor(color, factor) {
    const hex = color.replace('#', '');
    const r = Math.min(255, Math.floor(parseInt(hex.substr(0, 2), 16) * (1 + factor)));
    const g = Math.min(255, Math.floor(parseInt(hex.substr(2, 2), 16) * (1 + factor)));
    const b = Math.min(255, Math.floor(parseInt(hex.substr(4, 2), 16) * (1 + factor)));
    return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
  }
  
  // 粒子系统方法
  createTrailParticles() {
    if (this.snake.length === 0) return;
    
    const head = this.snake[0];
    const headX = head.x * this.cellSize + this.cellSize / 2;
    const headY = head.y * this.cellSize + this.cellSize / 2;
    const realmIndex = this.realms.findIndex(realm => realm.name === this.currentRealm.name);
    
    // 根据境界调整粒子数量和效果
    const particleCount = 2 + realmIndex * 2; // 粒子数量递增
    const effectIntensity = (realmIndex + 1) / this.realms.length;
    
    // 基础轨迹粒子
    for (let i = 0; i < particleCount; i++) {
      this.particles.push({
        x: headX + (Math.random() - 0.5) * this.cellSize * 0.8,
        y: headY + (Math.random() - 0.5) * this.cellSize * 0.8,
        vx: (Math.random() - 0.5) * (2 + effectIntensity * 2),
        vy: (Math.random() - 0.5) * (2 + effectIntensity * 2),
        life: 1.0,
        decay: 0.02,
        size: Math.random() * (2 + effectIntensity * 2) + 1,
        color: this.currentRealm.color,
        type: 'basic'
      });
    }
    
    // 筑基期及以上：能量粒子
    if (realmIndex >= 1) {
      for (let i = 0; i < 2; i++) {
        this.particles.push({
          x: headX + (Math.random() - 0.5) * this.cellSize,
          y: headY + (Math.random() - 0.5) * this.cellSize,
          vx: (Math.random() - 0.5) * 3,
          vy: (Math.random() - 0.5) * 3,
          life: 1.5,
          decay: 0.015,
          size: Math.random() * 2 + 2,
          color: this.currentRealm.color,
          type: 'energy',
          pulsePhase: Math.random() * Math.PI * 2
        });
      }
    }
    
    // 金丹期及以上：流光粒子
    if (realmIndex >= 2) {
      for (let i = 0; i < 3; i++) {
        const angle = Math.random() * Math.PI * 2;
        this.particles.push({
          x: headX,
          y: headY,
          vx: Math.cos(angle) * (3 + Math.random() * 2),
          vy: Math.sin(angle) * (3 + Math.random() * 2),
          life: 2.0,
          decay: 0.01,
          size: Math.random() * 1.5 + 1.5,
          color: this.currentRealm.color,
          type: 'flow',
          angle: angle
        });
      }
    }
    
    // 元婴期及以上：爆发粒子
    if (realmIndex >= 3 && Math.random() < 0.3) {
      for (let i = 0; i < 5; i++) {
        const angle = (Math.PI * 2 * i) / 5;
        this.particles.push({
          x: headX,
          y: headY,
          vx: Math.cos(angle) * 4,
          vy: Math.sin(angle) * 4,
          life: 1.0,
          decay: 0.02,
          size: Math.random() * 2 + 2,
          color: this.currentRealm.color,
          type: 'burst'
        });
      }
    }
    
    // 化神期及以上：电光粒子
    if (realmIndex >= 4 && Math.random() < 0.4) {
      for (let i = 0; i < 3; i++) {
        this.particles.push({
          x: headX + (Math.random() - 0.5) * this.cellSize * 1.5,
          y: headY + (Math.random() - 0.5) * this.cellSize * 1.5,
          vx: (Math.random() - 0.5) * 6,
          vy: (Math.random() - 0.5) * 6,
          life: 0.8,
          decay: 0.025,
          size: Math.random() * 1 + 1,
          color: '#FFFFFF',
          type: 'lightning'
        });
      }
    }
    
    // 渡劫期：星光粒子
    if (realmIndex >= 5) {
      const starColors = ['#FFD700', '#FFFFFF', '#87CEEB', '#FF69B4', '#98FB98'];
      for (let i = 0; i < 4; i++) {
        this.particles.push({
          x: headX + (Math.random() - 0.5) * this.cellSize * 2,
          y: headY + (Math.random() - 0.5) * this.cellSize * 2,
          vx: (Math.random() - 0.5) * 4,
          vy: (Math.random() - 0.5) * 4,
          life: 2.5,
          decay: 0.008,
          size: Math.random() * 2 + 1,
          color: starColors[Math.floor(Math.random() * starColors.length)],
          type: 'star',
          twinkle: Math.random() * Math.PI * 2
        });
      }
    }
  }
  
  updateParticles() {
    for (let i = this.particles.length - 1; i >= 0; i--) {
      const particle = this.particles[i];
      
      // 更新位置
      particle.x += particle.vx;
      particle.y += particle.vy;
      
      // 更新生命值
      particle.life -= particle.decay;
      
      // 移除死亡粒子
      if (particle.life <= 0) {
        this.particles.splice(i, 1);
      }
    }
  }
  
  drawParticles() {
    this.particles.forEach(particle => {
      const alpha = particle.life;
      this.ctx.save();
      this.ctx.globalAlpha = alpha;
      
      // 根据粒子类型绘制不同效果
      switch (particle.type) {
        case 'energy':
          // 能量粒子 - 脉动效果
          const pulseSize = particle.size * (1 + Math.sin(Date.now() * 0.01 + particle.pulsePhase) * 0.3);
          const energyGradient = this.ctx.createRadialGradient(
            particle.x, particle.y, 0,
            particle.x, particle.y, pulseSize
          );
          energyGradient.addColorStop(0, particle.color);
          energyGradient.addColorStop(0.5, particle.color + '80');
          energyGradient.addColorStop(1, particle.color + '00');
          
          this.ctx.fillStyle = energyGradient;
          this.ctx.beginPath();
          this.ctx.arc(particle.x, particle.y, pulseSize, 0, Math.PI * 2);
          this.ctx.fill();
          break;
          
        case 'flow':
          // 流光粒子 - 拖尾效果
          const flowGradient = this.ctx.createRadialGradient(
            particle.x, particle.y, 0,
            particle.x, particle.y, particle.size * 2
          );
          flowGradient.addColorStop(0, particle.color);
          flowGradient.addColorStop(0.3, particle.color + 'AA');
          flowGradient.addColorStop(1, particle.color + '00');
          
          this.ctx.fillStyle = flowGradient;
          this.ctx.beginPath();
          this.ctx.arc(particle.x, particle.y, particle.size * 2, 0, Math.PI * 2);
          this.ctx.fill();
          
          // 核心亮点
          this.ctx.fillStyle = particle.color;
          this.ctx.beginPath();
          this.ctx.arc(particle.x, particle.y, particle.size * 0.5, 0, Math.PI * 2);
          this.ctx.fill();
          break;
          
        case 'burst':
          // 爆发粒子 - 强烈光芒
          const burstGradient = this.ctx.createRadialGradient(
            particle.x, particle.y, 0,
            particle.x, particle.y, particle.size * 1.5
          );
          burstGradient.addColorStop(0, '#FFFFFF');
          burstGradient.addColorStop(0.3, particle.color);
          burstGradient.addColorStop(1, particle.color + '00');
          
          this.ctx.fillStyle = burstGradient;
          this.ctx.beginPath();
          this.ctx.arc(particle.x, particle.y, particle.size * 1.5, 0, Math.PI * 2);
          this.ctx.fill();
          break;
          
        case 'lightning':
          // 电光粒子 - 闪烁效果
          if (Math.random() > 0.5) {
            const lightningGradient = this.ctx.createRadialGradient(
              particle.x, particle.y, 0,
              particle.x, particle.y, particle.size * 3
            );
            lightningGradient.addColorStop(0, '#FFFFFF');
            lightningGradient.addColorStop(0.5, '#87CEEB80');
            lightningGradient.addColorStop(1, '#87CEEB00');
            
            this.ctx.fillStyle = lightningGradient;
            this.ctx.beginPath();
            this.ctx.arc(particle.x, particle.y, particle.size * 3, 0, Math.PI * 2);
            this.ctx.fill();
          }
          
          this.ctx.fillStyle = '#FFFFFF';
          this.ctx.beginPath();
          this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
          this.ctx.fill();
          break;
          
        case 'star':
          // 星光粒子 - 闪烁星形
          const twinkle = Math.sin(Date.now() * 0.005 + particle.twinkle);
          const starSize = particle.size * (1 + twinkle * 0.5);
          
          // 星形光芒
          this.ctx.strokeStyle = particle.color + '80';
          this.ctx.lineWidth = 1;
          for (let i = 0; i < 4; i++) {
            const angle = (Math.PI * i) / 2;
            this.ctx.beginPath();
            this.ctx.moveTo(
              particle.x + Math.cos(angle) * starSize * 0.5,
              particle.y + Math.sin(angle) * starSize * 0.5
            );
            this.ctx.lineTo(
              particle.x + Math.cos(angle) * starSize * 2,
              particle.y + Math.sin(angle) * starSize * 2
            );
            this.ctx.stroke();
          }
          
          // 星形核心
          const starGradient = this.ctx.createRadialGradient(
            particle.x, particle.y, 0,
            particle.x, particle.y, starSize
          );
          starGradient.addColorStop(0, particle.color);
          starGradient.addColorStop(1, particle.color + '00');
          
          this.ctx.fillStyle = starGradient;
          this.ctx.beginPath();
          this.ctx.arc(particle.x, particle.y, starSize, 0, Math.PI * 2);
          this.ctx.fill();
          break;
          
        default:
          // 基础粒子
          const gradient = this.ctx.createRadialGradient(
            particle.x, particle.y, 0,
            particle.x, particle.y, particle.size
          );
          gradient.addColorStop(0, particle.color);
          gradient.addColorStop(1, particle.color + '00');
          
          this.ctx.fillStyle = gradient;
          this.ctx.beginPath();
          this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
          this.ctx.fill();
          break;
      }
      
      this.ctx.restore();
    });
  }
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
  @keyframes realmBreakthrough {
    0% {
      opacity: 0;
      transform: translate(-50%, -50%) scale(0.5);
    }
    20% {
      opacity: 1;
      transform: translate(-50%, -50%) scale(1.2);
    }
    80% {
      opacity: 1;
      transform: translate(-50%, -50%) scale(1);
    }
    100% {
      opacity: 0;
      transform: translate(-50%, -50%) scale(1);
    }
  }
  
  @keyframes realmBreakthroughText {
    0% {
      opacity: 0;
      transform: translate(-50%, -50%) scale(0.3) rotateY(-90deg);
    }
    20% {
      opacity: 1;
      transform: translate(-50%, -50%) scale(1.1) rotateY(0deg);
    }
    80% {
      opacity: 1;
      transform: translate(-50%, -50%) scale(1) rotateY(0deg);
    }
    100% {
      opacity: 0;
      transform: translate(-50%, -50%) scale(0.8) rotateY(90deg);
    }
  }
`;
document.head.appendChild(style);

// 启动游戏
window.addEventListener('DOMContentLoaded', () => {
  const game = new ImmortalSnakeGame();
  game.draw();
});